Created
April 18, 2011 23:35
-
-
Save alexfish/926521 to your computer and use it in GitHub Desktop.
Reverse an array in Ruby without .reverse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
i = 0 | |
j = array.length - 1 | |
while i < j do | |
last = array[j] | |
first = array[i] | |
array[i] = last | |
array[j] = first | |
i += 1 | |
j -= 1 | |
end | |
puts array |
spchetan11
commented
Aug 27, 2016
•
array = [1, 2, 3, 4, 5]
(array.count / 2).times do |i|
array[i], array[-(i + 1)] = array[-(i + 1)], array[i]
end
puts array
array = [1, 2, 3]
array_reversed = []
array.each do |x|
array_reversed.unshift x
end
def reverse(array)
rev = []
rev << array.pop until array.empty?
rev
end
def reverse(a)
a.length.times do |i|
a.insert(i, a.pop)
end
end
def reverse_array(arr)
length = arr.length
half_length = length / 2
(0...half_length).each do |i|
# Swap elements from the beginning and end of the array
arr[i], arr[length - 1 - i] = arr[length - 1 - i], arr[i]
end
return arr
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment