![]() |
In this article, we will cover rearranging array such that even positions are greater than odd in JavaScript. Example: Approaches
Using Reverse Iteration ApproachHere, 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 Javascript
Output
[ 2, 6, 3, 5, 4 ] Using the Element Swapping ApproachHere, 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
Output
[1, 4, 2, 6, 3, 8, 5, 7] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |