Java Program to Reverse an Array Without Using Another Array

Introduction

Reversing an array in place, without using an additional array, is a common algorithmic task. This can be done efficiently by swapping elements from the two ends of the array, moving towards the center.

Example Program

Here is a complete Java program that demonstrates how to reverse an array in place.

Example Code:

public class ReverseArrayInPlace {
    public static void main(String[] args) {
        // Example array
        int[] array = {1, 2, 3, 4, 5};

        // Print the original array
        System.out.println("Original Array: ");
        printArray(array);

        // Reverse the array in place
        reverseArray(array);

        // Print the reversed array
        System.out.println("Reversed Array: ");
        printArray(array);
    }

    // Method to reverse the array in place
    public static void reverseArray(int[] array) {
        int left = 0; // Start pointer
        int right = array.length - 1; // End pointer

        while (left < right) {
            // Swap elements at left and right indices
            int temp = array[left];
            array[left] = array[right];
            array[right] = temp;

            // Move the pointers towards the center
            left++;
            right--;
        }
    }

    // Method to print the array
    public static void printArray(int[] array) {
        for (int element : array) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
}

Explanation:

  1. Initialization:

    • The main method initializes an example array and prints it using the printArray method.
  2. Reverse the Array:

    • The reverseArray method reverses the array in place. It uses two pointers, left and right, to swap elements from the ends towards the center.
    • The left pointer starts from the beginning (index 0), and the right pointer starts from the end (index array.length - 1).
    • The elements at these two positions are swapped, and then the pointers are moved towards the center (left++ and right--).
    • This process continues until the left pointer is no longer less than the right pointer.
  3. Print the Array:

    • The printArray method is a utility method to print the elements of the array.

Output:

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

Conclusion

Reversing an array in place without using another array is an efficient way to reverse the elements of an array. The key idea is to use two pointers, one starting from the beginning and the other from the end, and swap their elements while moving towards the center. This approach has a time complexity of O(n) and a space complexity of O(1), making it optimal for this task. Understanding and implementing this algorithm enhances your ability to work with arrays and manipulate their elements effectively.

Comments