ARRAY REVERSING
Explanation:
Reversing an array means rearranging the elements such that the first element becomes
the last, the second element becomes second last and so on.
Example:
Input: arr[] = {1, 4, 3, 2, 6, 5}
Output: {5, 6, 2, 3, 4, 1}.
This can be solved in many approach’s but the simple approach is naive approach
[Naive Approach] Using a temporary array – O(n) Time and O(n) Space:
The idea is to use a temporary array to store the reverse of the array.
Step 1: Initialize an Array
• Create an array (list) with some elements.
Syntax:
arr = [1, 4, 3, 2, 6, 5]
Step 2: Create a Temporary Array of the Same Size
• Use an empty list to store reversed elements.
Syntax:
temp = [0] * len(arr)
Step 3: Copy Elements from Original Array to Temporary Array in Reverse Order
• Use a loop to copy elements in reverse order.
• The last element of arr should be the first element of temp, and so on.
Syntax:
for i in range(len(arr)):
temp[i] = arr[len(arr) - 1 - i]
Step 4: Copy Back from Temporary Array to Original Array
• Copy elements from temp back to arr.
Syntax:
for i in range(len(arr)):
arr[i] = temp[i]
Step 5: Print the Reversed Array
• Display the reversed array.
Syntax:
print("Reversed array:", arr)
Programs:
// C++ Program to reverse an array using temporary array
#include <iostream>
#include <vector>
using namespace std;
void reverseArray(vector<int> &arr) {
int n = [Link]();
vector<int> temp(n);
for(int i = 0; i < n; i++)
temp[i] = arr[n - i - 1];
for(int i = 0; i < n; i++)
arr[i] = temp[i];
int main() {
vector<int> arr = { 1, 4, 3, 2, 6, 5 };
reverseArray(arr);
for(int i = 0; i < [Link](); i++)
cout << arr[i] << " ";
return 0;
}
// Java Program to reverse an array using temporary array
import [Link];
class GfG {
static void reverseArray(int[] arr) {
int n = [Link];
int[] temp = new int[n];
for (int i = 0; i < n; i++)
temp[i] = arr[n - i - 1];
for (int i = 0; i < n; i++)
arr[i] = temp[i];
public static void main(String[] args) {
int[] arr = { 1, 4, 3, 2, 6, 5 };
reverseArray(arr);
for (int i = 0; i < [Link]; i++)
[Link](arr[i] + " ");
}
# Python Program to reverse an array using temporary array
def reverseArray(arr):
n = len(arr)
temp = [0] * n
for i in range(n):
temp[i] = arr[n - i - 1]
for i in range(n):
arr[i] = temp[i]
if __name__ == "__main__":
arr = [1, 4, 3, 2, 6, 5]
reverseArray(arr)
for i in range(len(arr)):
print(arr[i], end=" ")
TASK:
Problem Statement:
You are given an array of integers. Your task is to transform the array such that its elements appear in
reverse order. The first element moves to the last position, the second element moves to the second-last
position, and so on.
Write a function to achieve this transformation in-place (without using extra space).
Input Format:
• The first line contains an integer N — the size of the array.
• The second line contains N space-separated integers representing the elements of the array.
Output Format:
• Print the reversed array as space-separated integers.
Input:5,6,7,8,9 output:9,8,7,6,5