Alternative sorting of an array in JavaScript


We are required to write a JavaScript function that takes in an array of Numbers as the first and the only argument.

The job of our function is to sort the elements present in the array in an alternate fashion.

By alternate we mean the following −

Suppose we have an array arr that contains only four elements for the time being. Then our function should shuffle the elements of the array such that −

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

Note that there can be more than one possible solution for a given array, we are just required to return any of the possible solutions.

For example −

If the input array is −

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

Then one possible output could be −

const output = [ 3, 6, 2, 5, 1, 4 ];

Example

Following is the code −

const arr = [1, 2, 3, 4, 5, 6];
const alternateSort = (arr = []) => {
   arr.sort((a, b) => a - b);
   const N = arr.length;
   let mid = Math.floor(N/2);
   if(N % 2 !== 0){
      mid++;
   };
   const small = arr.splice(0, mid);
   const big = arr.splice(0,arr.length);
   for(let i = 0; i < N; i++){
      if(i % 2 === 0){
         arr[i] = small.pop()
      }else{
         arr[i] = big.pop()
      };
   };
};
alternateSort(arr);
console.log(arr);

Output

Following is the console output −

[ 3, 6, 2, 5, 1, 4 ]

Updated on: 18-Jan-2021

469 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements