Search code examples
c#arraysreverse

Reverse an array without using Array.Reverse()


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.


Solution

  • 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.