How to Reverse an Array?

Given an array (or string), the task is to reverse the array/string.

Example :

Input  : arr[] = {1, 2, 3}
Output : arr[] = {3, 2, 1}

To reverse an array, we will use the concept of swapping. First, the problem strategy will be discussed followed by two approaches coded in C++.

In short, set two pointers at the start and end of the array and start iterating over it till the (length of array)/2. For every idx, swap array[idx] with array[length - idx]

Psuedo Code:

void reverseArray(int[] arr) {
   start = 0 
   end = arr.length - 1 
   while (start < end) {
       // swap arr[start] and arr[end]
       int temp = arr[start]
       arr[start] = arr[end]
       arr[end] = temp
       start = start + 1
       end = end - 1
   }
}