How to reverse an array

The problem at hand is to reverse the elements of an array. Given an array of elements. The task is to modify the array in such a way that the elements are rearranged in reverse order.

For example, if we have an array [1, 2, 3, 4, 5], the goal is to transform it into [5, 4, 3, 2, 1].

The objective of the problem is to implement a function or method that takes an array as input and returns the reversed array. The reversal should be done in-place, meaning that the original array should be modified rather than creating a new array.

The problem can be approached by using two pointers. One pointing to the beginning of the array and the other pointing to the end. By swapping the elements at these positions and progressively moving the pointers towards each other. The array can be reversed efficiently.

The complexity analysis mentioned earlier explains the time and space requirements of the algorithm used to solve this problem.

The process to reverse an array in Java involves the following steps:

Efficient Solution:

  1. Initialize two pointers, start and end, where start points to the first element of the array and end points to the last element of the array.
  2. Swap the elements at the start and end positions.
  3. Move the start pointer to the next element and the end pointer to the previous element.
  4. Repeat steps 2 and 3 until the start pointer surpasses the end pointer.

This process ensures that each element in the array is swapped with its corresponding element on the opposite side of the array, effectively reversing the array.


public class ArrayReverse {
    public static void main(String[] args) {
        int[] myArray = {1, 2, 3, 4, 5};
        
        System.out.println("Original Array:");
        printArray(myArray);
        
        reverseArray(myArray);
        
        System.out.println("Reversed Array:");
        printArray(myArray);
    }
    
    public static void reverseArray(int[] arr) {
        int start = 0;
        int end = arr.length - 1;
        
        while (start < end) {
            // Swap elements at start and end positions
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            
            // Move start pointer to the next element
            start++;
            
            // Move end pointer to the previous element
            end--;
        }
    }
    
    public static void printArray(int[] arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

Output:


Original Array:
1 2 3 4 5
Reversed Array:
5 4 3 2 1

Time Complexity : The time complexity of the array reversal algorithm is O(n), where n is the number of elements in the array. This is because we iterate over half of the array (from the start to the middle) and perform a constant-time swap operation for each pair of elements. Since we only traverse half of the array, the time complexity is linearly proportional to the size of the input.

Space Complexity : The space complexity of the algorithm is O(1) since it uses a constant amount of additional memory to store the start and end pointers and a temporary variable for swapping the elements. The space required does not depend on the size of the input array.

Overall, the algorithm is efficient and can reverse an array in-place without requiring additional memory proportional to the input size.

Naive Approach:

One simple and straightforward approach to reversing an array is to create a new array and iterate through the original array in reverse order. We can copy each element from the original array to the new array starting from the last index.

Here’s the step-by-step process for the naive approach:

  1. Create a new array reversedArray of the same length as the original array.
  2. Initialize a variable index with the value of the last index of the original array.
  3. Iterate over the original array in a loop, starting from the first element.
  4. At each iteration, assign the current element of the original array to reversedArray[index].
  5. Decrement index by 1.
  6. Once the loop finishes, reversedArray will contain the reversed elements of the original array.

Here’s an example implementation in Java:


public class ArrayReverse {
    public static void main(String[] args) {
        int[] arr = {7, 2, 9, 1, 5};
        int[] reversedArray = reverseArray(arr);
        
        System.out.println("Reversed Array:");
        printArray(reversedArray);
    }
    
    public static int[] reverseArray(int[] arr) {
        int[] reversedArray = new int[arr.length];
        int index = arr.length - 1;
        
        for (int i = 0; i < arr.length; i++) {
            reversedArray[index] = arr[i];
            index--;
        }
        
        return reversedArray;
    }
    
    public static void printArray(int[] arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

Output:

In this approach, we create a new array and copy the elements from the original array in reverse order. This method requires additional memory to store the reversed array, making it less efficient in terms of space complexity compared to the in-place reversal approach discussed earlier.


Reversed Array:
5 1 9 2 7

Suggestions:

Factorial of a Number Full Explanation With Examples

Check Tree is a BST or not Full Explanation

Postorder Traversal in Binary Search Tree With Full Explanation

Preorder Traversal In Binary Search Tree Full Explanation With Example

Inorder Traversal in Binary Search Tree Full Explanation

Binary Search Tree Traversal With Full Examples And Explanation

Difference Between Binary Tree and Binary Search Tree With Complete Examples

Searching in Binary Search Tree With Full Explanation

Binary Search Tree With Full Explanation And Examples

Minimize the maximum difference between heights

Write a program to cyclically rotate an array by one

Find the Union and Intersection of the two sorted arrays

Move all the negative elements to one side of the array

Next Permutation in c++ || FlutterTPoint With examples

Kth max and min element of an array

Kadaneโ€™s Algorithm In JavaScript With Example

How to reverse an array

Find the Maximum and Minimum element in an Array

Sorting An Array In JavaScript

Donโ€™t miss new tips!

We donโ€™t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Translate ยป
Scroll to Top