Special type of sorting algorithm in JavaScript

JavascriptWeb DevelopmentFront End Technology

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

The function should sort the array based on the following conditions −

  • All even numbers are sorted in increasing order

  • All odd numbers are sorted in decreasing order

  • The relative positions of the even and odd numbers remain the same

For example −

If the input array is −

const arr = [12, 17, 15, 24, 1, 6];

Then the output should be −

const output = [6, 17, 15, 12, 1, 24];

Example

Following is the code −

const arr = [12, 17, 15, 24, 1, 6];
const specialSort = (nums = []) => {
   const oddArr = [], evenArr = [];
   for (let i = 0; i < nums.length; i++){
      if (nums[i] & 1) {
         oddArr.push(i);
      } else {
         evenArr.push(i);
      }
   }
   nums.sort((a, b) => a - b);
   let odd = oddArr.length - 1, even = 0;
   const res = [];
   for (let i = 0; i < nums.length; i++){
      if (nums[i] & 1) {
         res[oddArr[odd--]] = nums[i];
      } else {
         res[evenArr[even++]] = nums[i];
      }
   }
   return res;
}

Output

Following is the console output −

[ 6, 17, 15, 12, 1, 24 ]
raja
Published on 22-Jan-2021 07:04:21
Advertisements