Arrays: Program to reverse an array


In this article, we will reverse an array i.e. change the location of each element such that first element becomes last and last element becomes first and so on.

 

To reverse an array, we swap the elements. For e.g. the first element is swapped with last element.
The second element is swapped with second last element, and so on.

 
Algorithm
  1. Initialize two pointers 'start' and 'end'. start points at index 0 and end points at last element
  2. Loop through the array till start is less than end
  3. Swap the elements at start and end index position using the temp variable
  4. Increment the start pointer and decrement the end pointer
  5. After loop ends, print the array
 
Complexity

Time Complexity : O(n) , where n is the number of elements in the array
Space Complexity: O(1)

 
Java Code
import java.util.*;

    class ReverseAnArray
    {
    
      static void revereseArray(int[] arr) {

        int start = 0 ;
        int end = arr.length - 1 ;

        while (start < end) {
            // swap arr[start] and arr[end]
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start = start + 1;
            end = end - 1;
        }
      }
    
      public static void main(String[] args){

        int arr[]={1,2,3,4,5};
        System.out.print("Before Reversing array : ");

        for(int i = 0; i < arr.length; i++)
        {
          System.out.print(arr[i]+" ");
        }
        System.out.println("\n");
        
        revereseArray(arr);
        System.out.print("After Reversing array : ");

        for(int j = 0; j < arr.length; j++)
        {
          System.out.print(arr[j]+" ");
        }
        
      }
 }
 
Output

Before Reversing array : 1 2 3 4 5
After Reversing array : 5 4 3 2 1



Thanks for feedback.



Read More....
Check if an array is a min heap
Convert a sorted array into a binary search tree - recursive approach
Print the elements of an array
Find the kth largest element in the array
Find the kth smallest element in the array
Merge two sorted arrays