Special type of sorting algorithm in JavaScript


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 ]

Updated on: 22-Jan-2021

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements