Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse an array without using Array.Reverse()

Tags:

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.

like image 486
xorpower Avatar asked May 22 '11 13:05

xorpower


1 Answers

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.

like image 132
Petar Minchev Avatar answered Nov 04 '22 09:11

Petar Minchev