Large to Small Sorting Algorithm of already sorted array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Suppose we have an array of integers that is already sorted in the increasing order. We are required to write a JavaScript function that without using the inbuilt Array.prototype.sort() method sorts the array like the following −

  • First number should be the maximum

  • Second number should be the minimum

  • Third number should be the 2nd maximum

  • Fourth number should be the 2nd minimum

  • And so on.

For example −

If the input array is −

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

Then the output should be −

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

Example

Following is the code −

const arr = [1, 2, 3, 4, 5, 6];
const alternativeSort = (arr = []) => {
   const res = [];
   let left = 0;
   let right = arr.length - 1;
   while (res.length < arr.length) {
      res.push(arr[right]);
      if (left !== right) {
         res.push(arr[left]);
      }
      left++;
      right--;
   };
   return res;
};
console.log(alternativeSort(arr));

Output

Following is the console output −

[ 6, 1, 5, 2, 4, 3 ]
raja
Updated on 20-Jan-2021 07:03:28

Advertisements