How to Reverse an Array in C#

  1. Write an Algorithm to Reverse an Array in C#
  2. Use the Array.Reverse() Method to Reverse an Array in C#
  3. Use the Enumerable.Reverse() Method to Reverse an Array in C#
  4. Conclusion
How to Reverse an Array in C#

This tutorial will teach you different ways to reverse an array in C#, including predefined methods. Generally it requires the creation of a temp variable to store the first index value of an array temp = arr[0], store the second index value in arr[0] like arr[0] = arr[1], and store the temp value in arr[1].

It is a general concept of reversing a short array, and loops can help handle the reverse operations on the large arrays in C#.

Write an Algorithm to Reverse an Array in C#

The art of swapping is extremely efficient in reversing an array in C#. It’s important to define a pair of variables named startIndex and endIndex and initialize their values with 0 and n-1, respectively, where n represents the length of an array.

You can implement the concept of swapping values of both variables and incrementing the value of startIndex by one means +1 and decrement in the endIndex by one (-1) into an algorithm in C# using the for loop. Repeat this step until the startIndex value is less than the endIndex value and print the array as a reversed array.

It’s a simple approach to reverse an array without using some auxiliary space only by interchanging values. Hence, the time complexity of the reverse array is O(n), and its space complexity is O(1).

You must iterate only through the first half of an array arr.Length / 2. Iterating through the whole array, arr.Length means the array will be reversed twice and output the same result as the original array.

using System;

public class reverseArrayAlgo {
  public static void Main(string[] args) {
    // create an array containing five integer values
    int[] expArray = { 4, 5, 6, 7, 8 };

    // display the original array
    Console.Write("The elements of the original array: ");
    for (int rep = 0; rep < expArray.Length; rep++) {
      Console.Write(expArray[rep] + " ");
    }

    // call a method that contains the algorithm to reverse the `expArray` array
    arrayReverse(expArray, 0, (expArray.Length - 1));

    // display the reversed array
    Console.Write("\r\nThe elements of the reversed array: ");
    for (int repo = 0; repo < expArray.Length; repo++) {
      Console.Write(expArray[repo] + " ");
    }
  }

  // create a method to reverse an array
  public static void arrayReverse(int[] expArray, int startIndex, int endIndex) {
    while (startIndex < endIndex) {
      int objTemp = expArray[startIndex];
      expArray[startIndex] = expArray[endIndex];
      expArray[endIndex] = objTemp;
      startIndex++;
      endIndex--;
    }
  }
}

Output:

The elements of the original array: 4 5 6 7 8

The elements of the reversed array: 8 7 6 5 4

Use the Array.Reverse() Method to Reverse an Array in C#

It belongs to the Array class in the System namespace and is an efficient way to reverse an array in C#. It processes the one-dimensional array by taking it as an argument to reverse its format so that you can receive a reversed array as an output.

Instead of creating a new array, it modifies the original array. You can use the Enumerable.Reverse() method if you’re unsatisfied with the original array’s modification available in the System.Linq namespace.

As a static method on the array type, it works by overwriting the existing elements or values of the specified array without any auxiliary space or array.

It throws multiple types of exceptions when an array is null or multidimensional; the index is less than the lower bound of the array, the length is less than zero, or the index and length do not specify a valid range in the array. After a call to this method, the elements at expArray[repo] (where expArray represents an array and repo is an index in the array) move to expArray[i] where i equals to:

(myArray.Length + myArray.GetLowerBound(0)) - (i - myArray.GetLowerBound(0)) - 1

This method is an O(n) operation where n represents the length of an array. The parameter value type passed to this method is System.Array, which represents the one-dimensional array to reverse.

Example Code:

using System;

public class reverseArrayAlgo {
  public static void Main(string[] args) {
    // create an array containing five integer values
    int[] expArray = { 4, 5, 6, 7, 8 };

    // display the original array
    Console.Write("The elements of the original array: ");
    for (int rep = 0; rep < expArray.Length; rep++) {
      Console.Write(expArray[rep] + " ");
    }

    // call the `Array.Reverse()` method to reverse the `expArray` array by passing it through the
    // method's parameter
    Array.Reverse(expArray);

    // display the reversed array
    Console.Write("\r\nThe elements of the reversed array: ");
    for (int repo = 0; repo < expArray.Length; repo++) {
      Console.Write(expArray[repo] + " ");
    }
  }
}

Output:

The elements of the original array: 4 5 6 7 8

The elements of the reversed array: 8 7 6 5 4

Use the Enumerable.Reverse() Method to Reverse an Array in C#

It is a useful way to reverse the order of elements in an array without modifying the original or underlying array by creating a new sequence of elements in the reversed order. Invoke the Enumerable.Reverse() method to invert the order of an array’s element, which is more convenient and easier to read than any other method or custom reverse algorithm.

It belongs to the System.Linq namespace and returns a sequence whose elements correspond to the input sequence in reverse order. Its value, which stores all the information necessary to perform the reverse operation, is an immediate return object implemented by deferred execution.

You can use the foreach or call the Getnumerator method directly to enumerate the object for the perfect execution of this method. Unlike OrderBy, the Enumerable.Array() as a sorting method does not consider the actual values in determining the order.

Example Code:

using System;
using System.Linq;

public class reverseArrayAlgo {
  public static void Main(string[] args) {
    // create an array containing five integer values
    int[] expArray = { 4, 5, 6, 7, 8 };

    // display the original array
    Console.Write("The elements of the original array: ");
    for (int rep = 0; rep < expArray.Length; rep++) {
      Console.Write(expArray[rep] + " ");
    }

    // call the `Enumerable.Reverse()` method to reverse the `expArray` array by passing it through
    // the method's parameter
    int[] reverse = Enumerable.Reverse(expArray).ToArray();

    // another alternative to display the reverse array
    // Console.WriteLine(String.Join(',', reverse));

    // display the reversed array
    Console.Write("\r\nThe elements of the reversed array: ");
    for (int repo = 0; repo < reverse.Length; repo++) {
      Console.Write(reverse[repo] + " ");
    }
  }
}

Output:

The elements of the original array: 4 5 6 7 8

The elements of the reversed array: 8 7 6 5 4

Conclusion

This tutorial discussed three ways to reverse an array in C#. This tutorial contains simplified and optimized examples of the executable C# code for profound understanding.

Every reverse method has its unique properties and advantages over the other. Choose the one that best suits your needs.

Syed Hassan Sabeeh Kazmi avatar Syed Hassan Sabeeh Kazmi avatar

Hassan is a Software Engineer with a well-developed set of programming skills. He uses his knowledge and writing capabilities to produce interesting-to-read technical articles.

GitHub

Related Article - Csharp Array