25

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.

Palec
  • 12,743
  • 8
  • 69
  • 138
xorpower
  • 17,975
  • 51
  • 129
  • 180

23 Answers23

60

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.

Palec
  • 12,743
  • 8
  • 69
  • 138
Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
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.

Palec
  • 12,743
  • 8
  • 69
  • 138
  • 2
    By the way, CoreCLR adds a generic `Array.Reverse()` that performs better and is [simpler to read](https://github.com/dotnet/coreclr/blob/ea9bee5ac2f96a1ea6b202dc4094b8d418d9209c/src/mscorlib/src/System/Array.cs#L1704-L1713). It was proposed in [issue #2352](https://github.com/dotnet/corefx/issues/2352). – Palec Mar 29 '17 at 16:10
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]);
        }
  • 5
    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. – bornfromanegg Nov 11 '19 at 15:12
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++;
}
Kon
  • 27,113
  • 11
  • 60
  • 86
1
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;
 }
  • Please add also an explanation what your answer (meaning code) does. – mnille Aug 18 '16 at 09:38
  • 1
    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. – Vince Bowdren Aug 18 '16 at 11:10
  • What does this add that was not already provided by [this answer](https://stackoverflow.com/a/6088313/7111561) 5 years earlier? – derHugo Jul 26 '23 at 09:11
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];
    }
}
Max
  • 109
  • 1
  • 4
  • 1
    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. – Alexei Levenkov Jun 06 '17 at 16:37
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]);
}
  • 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 – derHugo Jul 26 '23 at 09:14
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.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
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];
  }
Manoz
  • 6,507
  • 13
  • 68
  • 114
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);

            }
Rehman Ali
  • 23
  • 1
  • 8
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;
SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
Ramazan Kilimci
  • 109
  • 1
  • 7
  • 4
    please provide some explanation for your answer for clarification and avoid posting code only answers. – Saeed Zhiany Nov 03 '19 at 05:17
  • Sorry about that, that was my first time and I didn't want to break my code block. Thought comments would be enough. Next I provide enough explanation. Thank you for the feedback. – Ramazan Kilimci Nov 04 '19 at 13:10
0

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.

Fourth
  • 9,163
  • 1
  • 23
  • 28
  • 4
    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++)` – The Muffin Man May 07 '14 at 03:59
  • @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. – Cadde Dec 22 '14 at 09:35
  • I get asked these types of questions all the time in interviews. – The Muffin Man Dec 22 '14 at 17:32
  • this crates a new array instead of actually reversing the array. – bleepzter Apr 12 '17 at 00:57
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 :)

Marino Šimić
  • 7,318
  • 1
  • 31
  • 61
  • 1
    This is probably the most common interview question for programming jobs :) Using `.reverse()` does not cut it for that situation :) – Juha Untinen Mar 06 '15 at 09:22
  • 1
    This code doesn't work for his example (1, 3, 4, **9**, 8)! – kame Oct 09 '15 at 18:16
  • 1
    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. – bleepzter Apr 12 '17 at 00:55
  • 1
    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. – RoboticRenaissance Jul 18 '17 at 19:10
  • @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. – bornfromanegg Nov 11 '19 at 15:16
0

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();
Jim Simson
  • 2,774
  • 3
  • 22
  • 30
0

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]);
}
-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
    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. – bleepzter Apr 12 '17 at 00:53
-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.

Sam
  • 7,252
  • 16
  • 46
  • 65
-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

Alireza
  • 126
  • 1
  • 14
  • 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](https://stackoverflow.com/a/43098667/7111561) – derHugo Jul 26 '23 at 09:06
-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.

Steve
  • 1
  • 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. – Alexei Levenkov Jun 06 '17 at 16:35
-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
    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. – Igor Goyda Mar 13 '21 at 10:00
-1

Here is an example of reversing an array using the Length() function and a simple for loop.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int[] arr = new int[] {4, 8, 2, 9, 5, 5};
            
            int length = arr.Length;
            
            for(int i = 0; i < arr.Length; i++)
            {
               Console.WriteLine(arr[length-1] + " ");
               length = length - 1;
            }            
        }        
    }
}
Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
  • This is just an overly complicated way of writing [this](https://stackoverflow.com/a/50213993/7111561) ... and is still not what is asked for .. the question is **not** "How to print elements of an array in reversed order" .. but rather "How to reverse elements within an array" – derHugo Jul 26 '23 at 09:16
-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);
Pang
  • 9,564
  • 146
  • 81
  • 122
-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]);
   }   
  • 3
    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. – Alexei Levenkov Jun 06 '17 at 16:32
  • 3
    (and exactly the same as another "answer" to this question https://stackoverflow.com/a/31829476/477420) – Alexei Levenkov Jun 06 '17 at 16:38
  • @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) – Mahesh Sutar Jun 16 '17 at 08:26
  • 2
    I have no idea what you tried, but code in the post has no way to print less commas than numbers. – Alexei Levenkov Jun 16 '17 at 14:25