Reversing an Arrray

/ / 0 Comments

Array Reversing : To reverse an array or to perform any operation we must know some basics. As you must be knowing that an array is a bucket of homogenous items.

To be more precise, an array can only contain elements of the same type i.e. [“A”, “B”, ”C”] which is an array of strings, or [1,2,3] which is an array of integer type. 
The size of the array is defined at the time of initialization, which makes the array a fix-sized data structure.

Let’s take an example, we have an array of [1,2,3,4] and we need to reverse it which in turn will be [4,3,2,1].

We can reverse the array in many ways, but here we will be looking at the two best possibilities. The first method will use an auxiliary array and the second will use just a temporary variable.

Let’s check our first method:

public  int[] ReverseArray()
{
    int [] initialArray = {1.2,3,4};
	int[] reversedArray = new int[initialArray.Length];
	int len = initialArray;          
   
	for (int i = 0; i < len-1; i ++)
	{
		reversedArray[i] = initialArray[len-1];
		len--;
	}

	return arr;
}

Explanation:

  • Declaring and setting the array which we want to reverse. 

    int [] initial array = new array {1,2,3,4}

  • //As our 1st method will be of using some extra space we will be declaring //one more array variable to store the result. The size of the array will be of the same size as the original array

     int [] reversedArray = new int[initialArray];

  • //A variable for getting the length of the original array. 

    Int length = initialArray.Length;

  •  //The logic here is we will start traversing the array from the 0th element (as the first index of an array starts from zero) to the maximum index of the array. In our case, it will be 3.

  • //We will simply store the last element value of the original array to the 1st element in the reversed array and after that, we will decrement the length value. 

for (int i = 0 ;  i < length -1; i++ )
{
   reversedArray[i] = initialArray[length-1];
   length -- ;
}

Other Resource:

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

0 Comments