简体   繁体   中英

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.

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.

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.

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;
 }

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]);
        }

// 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];
    }
}
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]);
}
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++;
}

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.

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];
  }

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);

            }

You can use this method.

public int[] Reversing(int[] array)
    {
        int[] newArray = new int[array.Length];

        for (int i = 0; i < array.Length; i++)
        {
            newArray[i] = array[array.Length -(i+1)];
        }
        return newArray;
    }
//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;

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.

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 :)

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();
    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;
    }

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;
            }            
        }        
    }
}

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]);
}
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()
}
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.

It is better to use Array.Reverse method

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

You can read more description Here

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.

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);

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]);
   }   
   function printReverse(arr) {
      for(var i = arr.length - 1; i >= 0; i--){

    console.log(arr[i]);
      }
   }
printReverse([1, 2, 3, 6, 47, 88]);

 function printReverse(arr) { for (var i = arr.length - 1; i >= 0; i--) { console.log(arr[i]); } } printReverse([1, 2, 3, 6, 47, 88])

You can just loop backwards:

int[] arr= new int[] {1, 2, 3, 4, 6};
for(int i=arr.Length-1 ;i>= 0 ; i--)
{
    Console.WriteLine(arr[i].ToString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM