Uneven sorting of array in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the only argument. Our function should sort this array in such a way that after sorting, the elements should follow this pattern −

arr[0] < arr[1] > arr[2] < arr[3]....

For example, if the input to the function is −

const arr = [1, 5, 1, 1, 6, 4];

Then the output can (there can be more than one possible answer as well) be −

const output = [2, 3, 1, 3, 1, 2];

Example

The code for this will be −

const arr = [1, 5, 1, 1, 6, 4];
const unevenSort = (arr = []) => {
   arr.sort((a, b) => a - b);
   let mid = Math.floor(arr.length / 2);
   if(arr.length % 2 === 1){
      mid += 1;
   };
   let even = arr.slice(0, mid);
   let odd = arr.slice(mid);
   for(let i = 0; i < arr.length; i++){
      if(i % 2 === 0){
         arr[i] = even.pop();
      }else{
         arr[i] = odd.pop();
      };
   };
};
unevenSort(arr);
console.log(arr);

Output

The output in the console will be −

[ 1, 6, 1, 5, 1, 4 ]

Updated on: 20-Mar-2021

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements