How to use the Element Swapping Approach In Javascript
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( ", " )}]`); |
[1, 4, 2, 6, 3, 8, 5, 7]
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: