26

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.

1
  • 4
    @BoltClock - maybe we mean unicode... ɹɹɐ Commented May 22, 2011 at 13:53

23 Answers 23

61

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.

Sign up to request clarification or add additional context in comments.

1 Comment

for (int i = 0; i < arr.Length; i++) Console.WriteLine(arr[i] + ",");
17

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.

1 Comment

By the way, CoreCLR adds a generic Array.Reverse<T>() that performs better and is simpler to read. It was proposed in issue #2352.
3

That is So Simple Start loop from Array legth and so on watch code and you will get understand :)))

        int[] arr = new int[5] { 1, 2, 3, 4, 5 };

        for (int i = arr.Length-1; i >= 0; i--)
        {
            Console.WriteLine(arr[i]);
        }

1 Comment

This prints out the elements of the array in reverse order, but that is not what was asked for. The question was how to reverse the array.
2
int[] arr1 = {1,3,4,9,8};
int[] arr2 = new int[5];

int j = 0;

for(int i = arr1.Length - 1; i >= 0; i--)
{
  arr2[j] = arr1[i];
  j++;
}

3 Comments

This does not reverse an array. It creates a new array in reverse order.
Okay, so assign arr2 back to arr1 at the end. The basic gist is there.
that still doesn't reverse the original array.
2

I prefer a LINQ expression that uses an index:

using System.Linq;

int[] arr = { 1, 3, 4, 9, 8 };
arr = arr.Select((n, idx) => new {n, idx})
    .OrderByDescending(r => r.idx)
    .Select(r => r.n).ToArray();

Comments

1

Well, obviously you can just copy to a new array, in reverse order.

To do the operation "in place", you can work from both ends towards the middle: Load the first and last elements, then store them back, the first into the last location, and the last into the first location. Then do the second and the next-to-last, etc. If you have an even number of elements you do N/2 iterations. If an odd number you do (N-1)/2 iterations and leave the middle element where it was.

There are probably other algorithms that would be marginally faster when considering cache line size and other memory characteristics, but they wouldn't be worth it unless you were in a really performance-critical situation.

Comments

1

// without using Reverse method and without using additional array // try yield operator starting from the last element

public IEnumerable<int> Reverse (int[] array)
{
    for (int i = array.Length - 1; i >= 0; i--) {
        yield return array [i];
    }
}

1 Comment

While interesting it does not actually work as answer - OP asked to reverse the array and not to produce new array/sequence in reverse order.
1
char[] strx = { '1','2','3','4','5','6','7','8','9' };
int i = strx.Length;
string ktr ="";

while (i>0)
{
   i--;
   ktr += strx[i];

   if (i==0)
   {
      i = strx.Length;

      while (i > 0)
      {
         i--;
         strx[i] = ktr[i];
      }

   }
}
int j;
Console.WriteLine("Array strx in reverse order: ");
for (j = 0; j < strx.Length; j++ ) 
{
  Console.Write("{0}", strx[j]);
}

1 Comment

Note that - apart from this being limited to string - this uses a lot of new string allocations in ktr += strx[i]; (why not rather use a StringBuilder then?) .. it still doesn't reverse the original input like Array.Reverse which is what the question was about
1

You can try this, Without using additional temporary variable:

for(int i = left; i < right/2; i++)
{
    (nums[i], nums[right - i - 1]) = (nums[right - i - 1], nums[i]);
}

Comments

0

You can do this in many ways, from the most fast to the most stupid like:

int[] arr = new int[] { 1,2,3 };
arr = (from a in arr orderby a descending select a).ToArray();

But I cannot understand why are you pursuing such a futile quest, if that is to impress someone somewhere then use this instead of the for loops :)

5 Comments

This is probably the most common interview question for programming jobs :) Using .reverse() does not cut it for that situation :)
This code doesn't work for his example (1, 3, 4, 9, 8)!
No actually it doesn't. What this linq expression does is to crate a new array and assign it to the address of the arr variable. That's not sorting the existing array.
Here's the reason that they're assigned this 'futile quest'. Yes, it can be done automatically. But the interviewer is not looking for 'Can you tell me the function to use?' They're looking for the candidate's grasp on the actual workings of that function. Can they take the logical steps to get there? Basically, these types of questions can be answered the same way in any language, or in pseudocode, or in organizing a deck of physical cards.
@bleeptzer True, but the question wasn't to sort the array anyway. It was to reverse it. That's the main reason this answer is wrong.
0
for (int i = 0; i < array.Length - i; i++)
 {
   var value = array[array.Length - i - 1];
   array[array.Length - i - 1] = array[i];
   array[i] = value;
 }

3 Comments

Please add also an explanation what your answer (meaning code) does.
Hi Mohammad; your code might work, but with some context it would make a better answer; for example, you could explain how and why this proposed change would resolve the questioner's problem, perhaps including a link to the relevant documentation. That would make it more useful to them, and also more useful to other site readers who are looking for solutions to similar problems.
What does this add that was not already provided by this answer 5 years earlier?
0

I am not good at loops at all. But this is what seems simple to me -

 int[] array1 = { 1, 2, 3, 4, 5 };

 int[] reverseArray = new int[array1.Length];

 for (int i = 0; i <= array1.Length - 1; i++)
  {
    reverseArray[i] = array1[array1.Length - i - 1];
  }

Comments

0

This is the dynamic solution for reversing the array of any datatype.Some of the key points in my algorithm is first calculate the half of array length and add check to stop iteration when array indexes have same value.The stage having same indexes depict that it start the reverse operation again.So at this stage break the outer loop by using "goto Statement".

string[] unreversed = {"A","B","C","D","E","F","G","H","I","J","K"};
            int q=unreversed.Length;
            int t = q / 2;
            var temp1 = "A";
            for(int i = 0;i<unreversed.Length;i++)
            {
                q = q - 1;
                for(int k=q;k<=q;k++)
                {
                    if (unreversed[k] != unreversed[i] && i!=t)
                    {
                        temp1 = unreversed[i];
                        unreversed[i] = unreversed[k];
                        unreversed[k] = temp1;

                    }
                    else
                    {
                        goto printarray;

                    }

                }

            }
            printarray:
            foreach (var k in unreversed)
            {
                Console.WriteLine(k);

            }

Comments

0
//Create temp array with the same size.
int[] arrTemp = new int[arr.Length];
int i = 0;
//Assign last value of arr to first value of arrTemp
for (int j = arr.Length - 1; j >= 0; j--)
{
    arrTemp[i] = arr[j];
    i++;
}
arr = arrTemp;

1 Comment

please provide some explanation for your answer for clarification and avoid posting code only answers.
0

C# Solution

using System;
public class Program { public static void Main() { int[] arr = new int[] { 1, 2, 3, 4, 5, 6 };
 //---------------------------------------------------------------------------------------------------------------------
    // 1 Print Array as 1, 2, 3, 4, 5, 6
    //---------------------------------------------------------------------------------------------------------------------
    Console.WriteLine(string.Join(",", arr));
    //---------------------------------------------------------------------------------------------------------------------
    // 2> Write code to reverse it
    //---------------------------------------------------------------------------------------------------------------------     
    int temp=0;
    int left=0,right=arr.Length-1;
    while(left<right)
    {
        temp=arr[left];
        arr[left]=arr[right];
        arr[right]=temp;
        left++;
        right--;
    }       
    //---------------------------------------------------------------------------------------------------------------------
    // 3> Print reversed Array as 6, 5, 4, 3, 2, 1
    //---------------------------------------------------------------------------------------------------------------------
    Console.WriteLine(string.Join(",", arr));
}

Comments

-1

try something like:

var counter = 1;
var newArr = new int[arr.length];
for(int i = 0; i < arr.length; i++)
{
  newArr[i] = arr[arr.length - counter];
  counter++;
}

I didn't test that but it should be on the right track. Any reason you dont want to use Array.Reverse? Its probably a well-optimized version of the algorithm.

4 Comments

You do know that you can assign more than one variable in for loop? for(int i=0,counter = 1; i < arr.Length; i++,counter++)
@TheMuffinMan That is really useful and even after years of C# coding i have never come across that. Or maybe i have but have forgotten about it, either way, i feel like i learned something today.
I get asked these types of questions all the time in interviews.
this crates a new array instead of actually reversing the array.
-1
Stack stack=new Stack;
var newArr = new int[arr.length];

for(int i = 0; i < arr.length; i++)
{
  stack.push(arrr[i])
}
for(int i = 0; i < arr.length; i++)
{
  newarr[i]= stack.pop()
}

1 Comment

This solution works but it has the problem that it iterates through the array twice. Furthermore the usage of a stack adds to the inefficiency of the algorithm. An easier way to do it is to swap the first and last, second and second to last and so on elements... by iterating only once through the array and using a 3-way swap.
-1
int[] array1 = { 1, 2, 3, 4, 5 };

for (int x = 4; x < array1.Length && x != -1; x--)
{
    int tmp;
    tmp=array1[x];
    Console.Write("{0} ", tmp);
}

That's my solution for this.

Comments

-1

It is better to use Array.Reverse method

int[] arr ={1,3,4,9,8};
Array.Reverse(arr);

You can read more description Here

1 Comment

Better in which regard? Array.Reverse is for generic arrays (including multidimensional) and does a lot of casting and checks internally you can skip if you already know your type .. see this answer
-1
int[] triangles = new int[]{0,1,2,3}    
for (int j = triangles.Length; j > (triangles.Length / 2); j--)
                    {
                        var temp = triangles[j - 1];
                        triangles[j - 1] = triangles[triangles.Length - j];
                        triangles[triangles.Length - j] = temp;
                    }

I would prefer to reverse an array from the end of it. My solution's above.

1 Comment

So far does not look useful - this is essentially the same as accepted answer except for whatever reason you suggesting to iterate down... Please clarify why this is better approach.
-1
    public int[] Reverse(params int[] numbers)
    {
        for (int i = 0; i < numbers.Length / 2; i++)
        {
            int tmp = numbers[i];
            numbers[i] = numbers[numbers.Length - i - 1];
            numbers[numbers.Length - i - 1] = tmp;
        }

        return numbers;
    }

1 Comment

What was the point of suggesting the same answer as accepted one? That question has already answered and your answer did not add any value to the existing solution.
-2
Console.WriteLine("Enter a string");
string input = Console.ReadLine();

string s = "";
for (int i = input.Length-1 ; i >= 0; i--)
{
    s = s + input[i];
}
Console.WriteLine(s);

1 Comment

Wrong answer. The question is about reversing an array, not reversing a string.
-2

Can do this with single for loop..

   int[] arr ={1,3,4,9,8};


   for(int i=arr.length-1;i>=0;i--)
   {
      Console.Write(arr[i]);
   }   

4 Comments

This neither does what asked in the question (reverse array) nor produces output expected (has extra comma) - not sure why it is posted as answer.
(and exactly the same as another "answer" to this question stackoverflow.com/a/31829476/477420)
@AlexeiLevenkov I have tried it before posting as answer and it produces output as expected with comma (not extra). In this answer [link] (stackoverflow.com/a/31829476/477420) there is no need to use ToString() and also it doesn't produce answer as expected with comma(It will print on new line)
I have no idea what you tried, but code in the post has no way to print less commas than numbers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.