Reversing An Array

Reversing An Array
Reversing An Array

Introduction

An array is the most used data structure. An array is a collection of elements of similar data types. Suppose there are 50 students in your class and you want to store the name of every student in your program. One option is that you make 50 variables and store their names in these or the more optimal way is that you make an array of strings and store names of all in this array. Elements in arrays are stored in contiguous memory locations and the most important thing you should know about an array is that the name of an array is the pointer to the first element of the array. You can learn more about pointers here. If you want to learn more about arrays, you can check this link. In this blog, we’ll learn how we can reverse an array.

Suppose you are given an array like this:

123456

Now you are given the task of reversing this array i.e.

654321

We can reverse the arrays using various methods like the iterative method or the recursive method. Let’s see all these methods here:

Method 1: Iterative Method

Let’s discuss an algorithm to reverse the array iteratively:

Step 1. Take two pointers start and end and initialize them with start pointing at starting index of the array and end pointer pointing at the last index of the array.

           0                        1                          2                        3                          4                         5

123456

         ↑                                                                                                                ↑

        start                                                                                                           end

Step 2. Now run a for loop and keep swapping elements at start index with an element at end index.

blog banner 1
623451

         ↑                                                                                                                ↑

        start                                                                                                           end

Step 3. Increment the start pointer and decrement the start pointer by one i.e. start++ and end–.

623451

                               ↑                                                                  ↑

                              start                                                             end

And when you keep running your loop, you will reach a condition where your start pointer will surpass your end pointer, and at that moment, you will get your output i.e., a reversed array.

Let’s see its implementation in code:

C Program for reversing an array

#include <stdio.h>

Void reverseArray(int *arr, int size)
{
    //pointing at the start of the array
    int start = 0;
    //pointing at the end
    int end = size - 1;

    while (start <= end)
    {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}
int main()
{

    int num;
    scanf(“% d”, &num);

    //making an array
    int arr[num];

    //Taking input in the array
    for (int i = 0; i < num; i++)
    {
        scanf(“% d”, &arr[i]);
    }

    //calling a function which will reverse this array
    reverseArray(arr, num);

    //printing array after reversal
    for (i = num - 1; i >= 0; i–)
    {
        printf(“% d\n”, arr[i]);
    }

    return 0;
}
Output:

//size of array 
  5
//array given as input
1 2 3 4 5
//result printed by our program
5 4 3 2 1

C++ Program for reversing an array

#include <bits/stdc++.h>
using namespace std;

//function to reverse array
void reverseArray(int *arr, int n)
{
    //start pointing at the starting index of array
    int start = 0;
    //end pointing at the end index of the array
    int end = n - 1;
    while (start <= end)
    {
        //swapping the elements present at the start and end index of array
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

int main()
{
    int num;
    cin >> num;

    //taking input in the array
    int *arr = new int[num];
    for (int i = 0; i < num; i++)
    {
        cin >> arr[i];
    }

    reverseArray(arr, num);
    //printing array after reversal
    for (int i = 0; i < num; i++)
    {
        cout << arr[i] << " ";
    }
    return 0;
}
Output:
//size of array 
  5
//array given as input
1 2 3 4 5
//result printed by our program
5 4 3 2 1

JAVA Program for Reversing an Array

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        int n;
        Scanner s = new Scanner(System.in);
        //taking input of elements in the array
        System.out.print("Enter no. of elements in array:");
        n = s.nextInt();
        int arr[] = new int[n + 1];
        System.out.println("Enter all the elements:");

        for (int i = 0; i < n; i++) {
            arr[i] = s.nextInt();
        }
        System.out.print("Reversed array is : ");

        //printing the array
        for (int i = n - 1; i >= 0; i--) {
            System.out.print(arr[i] + " ");
        }

    }
}
Output:
Enter no of elements in the array:
5
Enter all elements
1 2 3 4 5
Reversed Array is:
5 4 3 2 1

This approach will reverse your array in O(N) time complexity and O(1) space complexity.

Method 2: Recursive Method

Let’s see another approach to reverse an array using Recursion.Here is the algorithm of this approach:

Step 1. Take two pointers as start and end.Initialize start with 0 and end with (size of array -1).

Step 2. Swap the values present at the start and end index of the array.

Step 3. Now call the recursion for the rest of the array, and you’ll get the reversed array as output. It’s that simple, isn’t it?

Let’s code it now :

C Program for reversing an array

#include<stdio.h>
void reverseArray(int * arr, int start, int end) {
  int temp;
  //base case
  if (start >= end)
    return;

  //small calculation
  temp = arr[start];
  arr[start] = arr[end];
  arr[end] = temp;
  //recursively calling the function
  reverseArray(arr, start + 1, end - 1);
}

int main() {

  int num;
  scanf("%d", & num);

  //making an array
  int arr[num];

  //Taking input in the array
  for (int i = 0; i < num; i++) {
    scanf("%d", & arr[i]);
  }

  //pointing at the start of the array 
  int start = 0;
  //pointing at the end 
  int end = num - 1;

  //calling a function that will reverse this array
  reverseArray(arr, start, end);

  //printing array after reversal
  for (int i = 0; i < num; i++) {
    printf("%d\n", arr[i]);
  }

  return 0;
}
Output:
//size of array 
  5
//array given as input
1 2 3 4 5
//result printed by our program
5 4 3 2 1

C++ Program for reversing an array

#include <bits/stdc++.h>
using namespace std;
 
//function to reverse array
void reverseArray(int* arr, int start, int end)
{
    if (start >= end)
      return;
     
    int temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
     
    // Recursive Function calling
    reverseArray(arr, start+1, end-1);
}  


int main(){
    int num;
    cin >> num;
    
    //taking input in the array
    int* arr = new int[num];
    for(int i = 0; i < num; i++){
        cin >> arr[i];
    }
    
     //start pointing at the starting index of array
    int start = 0;
    //end pointing at the end index of the array
    int end = num-1;

    reverseArray(arr, start, end);
    //printing array after reversal
    for(int i = 0; i < num; i++){
        cout << arr[i] << " ";
    }
    return 0;
}
Output:
//size of array 
  5
//array given as input
1 2 3 4 5
//result printed by our program
5 4 3 2 1

You can reverse an array in O(N) time complexity and O(N) space complexity by the above recursive way.

Method 3: Using List Slicing

In python, we can use list slicing to reverse an array. Using list slicing, you can reverse your array in O(N) time complexity.

def reverse(arr):
  //using slicing in python
  print( arr[::-1])
     
# Driver function to test above function
arr = [1, 2, 3, 4, 5, 6]
print(arr)
print("Reversed list:")
reverse(arr) 
Output: 
Reversed list: 6 5 4 3 2 1

So it’s super easy to reverse an array using list slicing in python. In the above code, we used the slicing method of python. If you want to know more about slicing in python, go ahead with this. slicing in python follows the syntax [start: end: step].

Here we have not given start and end values because, by default, they are assumed to be the starting and end index of the array, and we have given step as -1 because we are asking python to provide every element of the array by traversing from back to front.

Frequently Asked Questions

How can I reverse an array in C++?

You can reverse an array in C++ using recursion or by using loops i.e by. iterative method.

How do I print an array in reverse order?

You can print array in reverse order using a loop like this:

for(int i = size-1; i >= 0; i–){
cout << arr[i] << endl;
}

Can I reverse an array using another array?

Absolutely, You can but it’s not an optimized approach. You should try to reverse it using O(1) space complexity because increasing the space complexity of a program is not considered to be a good practice.

Can I reverse an array in less than O(N) time complexity?

No, you can’t do that because for reversing an array, you need to travel all the array elements in one traversal time complexity will be O(N).

Key Takeaways

In this article, you learned that you can reverse an array using various approaches like recursion or using list slicing in python. An array is the most asked data structure in interviews, so it’s mandatory to learn about different operations you can perform on an array.

You can explore more about arrays here . Here we discussed the time and space complexity of reversing an array. You should always try to find the space and time complexity of any program you write, as in the real world, we have to calculate in advance the time and space our program will take.

I hope this blog has made all concepts about reversing an array clear to you. Remember, Knowledge increases with sharing, so with whom are you going to share this blog next?