Reverse an array without using Array.Reverse()

xorpower picture xorpower · May 22, 2011 · Viewed 88.2k times · Source

How to reverse an array (in C#) without using Array.Reverse() method?

For example,

int[] arr = {1,3,4,9,8};
// some code here
Console.WriteLine(string.Join(",", arr));

should result in

8,9,4,3,1

I got this as an interview task.

Answer

Petar Minchev picture Petar Minchev · May 22, 2011

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.