Related Tags

array

# How to reverse the order of elements of the array

Ravi

## Overview

Consider that we’ve been given an array and know its size. Now, we want to write a function that reverses the order of elements present at odd indices of the array.

Example 1:

• Input: arr=[1,2,3,4,5]
• Output: [1,4,3,2,5]

Example 2:

• Input: arr=[11, 12, 0, 4, 3, 1, 2]
• Output: [11, 1, 0, 4, 3, 11, 2]

### How to reverse the order

Here, we use the stack data structure to reverse the elements in an odd indexed position.

The steps are as follows:

1. Loop through the array and push every odd indexed element onto the stack.
2. Loop through the array and replace every odd indexed element with the element popped from the stack.
• Time complexity: O(n)
• Space complexity: O(n)

### Code

Let’s view the code examples.

import java.util.Arrays;
import java.util.Stack;

class Main{

public static void reverseOddIndexedElements(int[] arr){
Stack<Integer> stack = new Stack<>();
for(int i=1; i<arr.length;i+=2) stack.push(arr[i]);
for(int i=1; i<arr.length;i+=2) arr[i] = stack.pop();
}

public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
System.out.println("Original Array - " + Arrays.toString(arr));
reverseOddIndexedElements(arr);
System.out.println("Modified Array - " + Arrays.toString(arr));
}
}
Try it out!

### Explanation

• Lines 6–10: We use the reverseOddIndexedElements() method which implements the above solution to reverse the elements at odd indexes.
• Line 13: We define an array of elements arr.
• Line 14: We print the arr.
• Line 15: We call the reverseOddIndexedElements() method with arr to reverse odd positioned elements in arr.
• Line 16: We print the reversed array.

RELATED TAGS

array

CONTRIBUTOR

Ravi
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time