Reverse an array without using Array.Reverse()

Basically, you are asked to reimplement Array.Reverse(Array). If you look at how it is implemented in the framework itself and ignore many technical details around, you’ll find that it just calls its three-parameter version (which reverses specified part of an array) on the whole array.

Array.Reverse(Array,Int32,Int32) is a while-loop that swaps elements and maintains two indexes:

  1. i points to the first element of the reversed part, and
  2. j points to the last element of the reversed part.

Rewritten to be substituted in place of // some code here in the question:

int i = 0;
int j = arr.Length - 1;
while (i < j)
{
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    i++;
    j--;
}

This is easier to grasp than the implementation using for-loop, does less arithmetic and elegantly evades the gotcha with double reversion.


The code to be substituted in place of // some code here in the question is:

for (int i = 0; i < arr.Length / 2; i++)
{
   int tmp = arr[i];
   arr[i] = arr[arr.Length - i - 1];
   arr[arr.Length - i - 1] = tmp;
}

You should iterate only through the first half of the array (arr.Length / 2). If you iterate through the whole array (arr.Length), it will be reversed twice, yielding the same element order as before it started.

Tags:

C#

Arrays

Reverse