Open In App

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

In this article, we will cover rearranging array 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:



Approaches

Using 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 palace 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




//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.




// 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]

Article Tags :