JavaScript Program to Rearrange Array such that Even Positioned are Greater than Odd
Last Updated :
29 Aug, 2024
In this article, we will cover rearranging arrays such that even positions are greater than odd in JavaScript.
Give there is an array that we need to rearrange in the pattern where the even positioned are greater than the odd positioned in JavaScript. We will see the code for each approach along with the output. Below are the possible approaches that will be discussed in this article:
Example:

Using the Reverse Iteration Approach
Here, in this approach 1 we will initially sort the given or input array in the descending order (high-low). Later, we iterate through the sorted descending order array and then place the largest value element at the even indices and the rest elements are at odd indices in the result array.
Example: In this example, we are using Reverse Iteration Approach in JavaScript
JavaScript
//Using Reverse Iteration
function rearrangeArrayUsingReverseIteration(arrayInput) {
const n = arrayInput.length;
const descSortedArray = arrayInput
.slice()
.sort((a, b) => b - a);
const rearrangedArray = [];
for (let i = 0; i < n; i++) {
if (i % 2 === 0) {
rearrangedArray[i] = descSortedArray.pop();
} else {
rearrangedArray[i] = descSortedArray.shift();
}
}
return rearrangedArray;
}
const inputArray = [2, 4, 3, 5, 6];
const rearrangedArray =
rearrangeArrayUsingReverseIteration(inputArray);
console.log(rearrangedArray);
Using the Element Swapping Approach
Here, in this approach, we will iterate through the array of elements and analyze the adjacent pairs of elements. For the even indexes in the array, we are checking if the current element is greater than the next element, and if it is greater, then we are swapping them to make the even indexed element greater and the odd indexed element a smaller element in the array.
Example: This example shows the use of the above-explained approach.
JavaScript
// Using Element Swapping
function rearrangeArrayUsingElementSwapping(
arrInput,
sizeOfArray
) {
for (let i = 0; i < sizeOfArray - 1; i++) {
if (i % 2 === 0) {
if (arrInput[i] > arrInput[i + 1]) {
[arrInput[i], arrInput[i + 1]] = [
arrInput[i + 1],
arrInput[i],
];
}
}
if (i % 2 !== 0) {
if (arrInput[i] < arrInput[i + 1]) {
[arrInput[i], arrInput[i + 1]] = [
arrInput[i + 1],
arrInput[i],
];
}
}
}
}
let arrayInput = [2, 1, 4, 3, 6, 5, 8, 7];
let totalSize = arrayInput.length;
rearrangeArrayUsingElementSwapping(arrayInput, totalSize);
console.log(`[${arrayInput.join(", ")}]`);
Output[1, 4, 2, 6, 3, 8, 5, 7]
Two-Pass Sorting Approach
- Sort the Array: First, sort the array in ascending order.
- Rearrange Elements: Create a new array where you place the largest elements at the even indices and the smallest elements at the odd indices.
Example:
JavaScript
function rearrangeArrayUsingTwoPassSorting(arrayInput) {
const n = arrayInput.length;
const sortedArray = arrayInput.slice().sort((a, b) => a - b);
const rearrangedArray = new Array(n);
let evenIndex = 0;
let oddIndex = n - 1;
for (let i = 0; i < n; i++) {
if (i % 2 === 0) {
rearrangedArray[i] = sortedArray[evenIndex++];
} else {
rearrangedArray[i] = sortedArray[oddIndex--];
}
}
return rearrangedArray;
}
const inputArray = [2, 4, 3, 5, 6];
const rearrangedArray = rearrangeArrayUsingTwoPassSorting(inputArray);
console.log(rearrangedArray);
Using Priority Queue (Min-Heap) and Manual Placement
This approach uses a priority queue to manage the elements and ensure that we place the largest elements at even indices and the smallest elements at odd indices. A priority queue helps efficiently manage the smallest and largest elements during the rearrangement.
Steps:
- Sort and Split: First, sort the array in ascending order. Then, use two priority queues (min-heap and max-heap) to manage elements for odd and even positions respectively.
- Fill Heaps: Insert the smallest elements into the min-heap for odd positions and the largest elements into the max-heap for even positions.
- Construct Result: Construct the resulting array by extracting elements from the heaps in the correct order.
Example:
JavaScript
function rearrangeArray(arrayInput) {
const n = arrayInput.length;
const sortedArray = arrayInput.slice().sort((a, b) => a - b);
const rearrangedArray = new Array(n);
const half = Math.ceil(n / 2);
let oddPointer = 0;
let evenPointer = half;
for (let i = 0; i < n; i++) {
if (i % 2 === 0) { // 1-based index odd position (0-based index even position)
rearrangedArray[i] = sortedArray[oddPointer++];
} else { // 1-based index even position (0-based index odd position)
rearrangedArray[i] = sortedArray[evenPointer++];
}
}
return rearrangedArray;
}
const inputArray = [2, 4, 3, 5, 6];
console.log(rearrangeArray(inputArray));
Similar Reads
Javascript Program For Rearranging A Linked List Such That All Even And Odd Positioned Nodes Are Together Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together, Examples: Input: 1->2->3->4Output: 1->3->2->4Input: 10->22->30->43->56->70Output: 10->30->56->22->43->70The important thing in this
3 min read
Javascript Program to Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7}Output : 4 5 3 6 2 7 1Inp
3 min read
Javascript Program to Rearrange positive and negative numbers in O(n) time and O(1) extra space An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If the
3 min read
PHP Program to Rearrange Array Such That arr[i] >= arr[j] if i is Even and arr[i]<=arr[j] if i is Odd and j < i Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7}Output : 4 5 3 6 2 7 1Inp
3 min read
Java Program to Print the Elements of an Array Present on Odd Position An array stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. In an array, if there are "N" elements, the array iteration starts from 0 and ends with "N-1". The odd positions in the array are those with even indexing and vice versa. E
3 min read
Javascript Program For Rearranging An Array In Maximum Minimum Form - Set 2 (O(1) extra space) Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Examples:Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Input: arr[] = {1, 2, 3, 4
5 min read
Java Program to Print the Elements of an Array Present on Even Position The task is to print all the elements that are present in even position. Consider an example, we have an array of length 6, and we need to display all the elements that are present in 2,4 and 6 positions i.e; at indices 1, 3, 5. Example: Input: [1,2,3,4,5,6] Output: 2 4 6 Input: [1,2] Output: 2 Appr
2 min read
Javascript Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples: Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6
2 min read
Java Program to Sort the Elements of an Array in Descending Order Here, we will sort the array in descending order to arrange elements from largest to smallest. The simple solution is to use Collections.reverseOrder() method. Another way is sorting in ascending order and reversing.1. Using Collections.reverseOrder()In this example, we will use Collections.reverseO
2 min read
Java Program to Sort the Elements of an Array in Ascending Order Here, we will sort the array in ascending order to arrange elements from smallest to largest, i.e., ascending order. So the easy solution is that we can use the Array.sort method. We can also sort the array using Bubble sort.1. Using Arrays.sort() MethodIn this example, we will use the Arrays.sort()
2 min read