-
Notifications
You must be signed in to change notification settings - Fork 255
/
Copy pathReverseAnArray.rb
41 lines (34 loc) · 863 Bytes
/
ReverseAnArray.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#Given an array reverse it without using extra-space
#Time-complexity: O(n), Auxiliary-space: O(1)
# Iterative
def reverse_array(a)
right=a.length-1
left=0
while(left<right)
#swap the elements
temp=a[left] #Swapping can be like done like this a[left],a[right]=a[right],a[left]
a[left]=a[right]
a[right]=temp
left+=1
right-=1
end
print a
end
reverse_array([1,2,3,4,5]) # => [5,4,3,2,1]
# Recursive
#driver program
def driver_program(a)
right=a.length-1
left=0
reverse_array(a,left,right)
print a
end
def reverse_array(a,left,right)
return if left>=right
#swap the elements
temp=a[left]
a[left]=a[right]
a[right]=temp
reverse_array(a,left+1,right-1)
end
driver_program([1,2,3,4,5]) # => [5,4,3,2,1]