When working with an array of integers that need to be sorted in a specific order, such as:
[1, -1, -3, 9, -2, -5, 4, 8,]
We must rearrange them so that the largest number is followed by the smallest number, then the second largest number followed by the second smallest number, and so on.
[9, -5, 8, -3, 4, -2, 1, -1 ]
While it's clear how to find the first largest and smallest numbers manually, making this process dynamic for all values in the array can be more challenging.
One approach involves using two variables, such as firstSmallest and firstLargest, pointing to the first and last index of the sorted array. By iterating through the array, we can increment firstSmallest and decrement firstLargest to store the desired arrangement into a new output array.
let unsortedArr = [1, 5, 8 , 7, 6, -1, -5, 4, 9, 5]
let output = [];
function meanderArray(unsorted){
let sorted = unsorted.sort((a, b) => a-b);
let firstSmallest = sorted[0];
let firstLargest = sorted[unsorted.length-1];
for(let i = 0; i <= sorted.length; i++){
//Increment firstSmallest and decrement firstLargest to generate the desired output
}
return output;
}
meanderArray(unsortedArr);
console.log(output);