Reverse Array

tags: swap two-pointers

Reverse the order of the given input array.

Solution Outline

  1. Initialize the index i to 0
  2. Swap the first element arrays[i] with last element arrays[length - i - 1]
  3. Repeat until index of middle i == length / 2.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def reverse(a)
  i = 0
  n = a.size
  middle =  n / 2
  
  for i in (0..middle)
    # swap the values at index i and n-i-1
    a[i], a[n-i-1] = a[n-i-1], a[i]
  end
end

a = [1,2,3,4,5,6,7,8,9]

reverse(a)

p a

One of the key concept in this code is that we can find numbers located at the end by using the size of the array and the loop index. The index is computed by : n-i-1 (one is needed to deal with the 0 based array access).

Two pointer approach:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def reverse(a)
  i = 0
  j = a.size - 1
  
  while i < j
    # swap the values at index i and j
    a[i], a[j] = a[j], a[i]
    i += 1
    j -= 1
  end
end

a = [1,2,3,4,5,6,7,8,9]

reverse(a)

p a