Reverse An Array | Program to Reverse an Array

0
253

Imagine you have a row of boxes, each containing something special. Let’s say you have 5 boxes, and inside each box is a different colored ball – red, blue, green, yellow, and orange. This row of boxes represents an array.

Now, reversing the array means changing the order of the boxes. Instead of having the red ball box first and the orange ball box last, you’ll switch them around. So, the orange ball box will come first, followed by the yellow, green, blue, and red ball boxes.

In terms of the array, reversing it means taking the elements (like the colored balls) that are in a certain order and putting them in the opposite order. It’s like flipping the array to see its contents from the end to the beginning, just like flipping the row of boxes to see the balls in the opposite order.

Here’s how you can reverse an array in both Java and Python:

Java:

public class ArrayReverse {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        reverseArray(arr);

        // Print the reversed array
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }

    public static void reverseArray(int[] arr) {
        int left = 0;
        int right = arr.length - 1;

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

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

Python:

def reverse_array(arr):
    left = 0
    right = len(arr) - 1

    while left < right:
        # Swap elements at left and right indices
        arr[left], arr[right] = arr[right], arr[left]

        # Move towards the center
        left += 1
        right -= 1

# Example usage
arr = [1, 2, 3, 4, 5]
reverse_array(arr)

# Print the reversed array
print(arr)

Both of these programs use a similar approach. They use two pointers, one starting from the beginning of the array and the other starting from the end. The elements at these pointers are swapped, and then the pointers move towards each other until they meet in the middle. This way, the array gets reversed!

Thank You!

LEAVE A REPLY

Please enter your comment!
Please enter your name here