Open In App

JavaScript Program to Rearrange Array such that Even Positioned are Greater than Odd

Last Updated : 29 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

SS

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);

Output
[ 2, 6, 3, 5, 4 ]

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);

Output
[ 2, 6, 3, 5, 4 ]

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:

  1. 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.
  2. Fill Heaps: Insert the smallest elements into the min-heap for odd positions and the largest elements into the max-heap for even positions.
  3. 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));

Output
[ 2, 5, 3, 6, 4 ]




Next Article

Similar Reads