Insert a number into a sorted array of numbers JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a sorted array of numbers as the first argument and a single number as the second argument.

The function should push the number specified as the second argument into the array without distorting the sorting of the elements.

We are required to do this without creating another array.

Example

const arr = [6, 7, 8, 9, 12, 14, 16, 17, 19, 20, 22];
const num = 15;
const findIndex = (arr, val) => {
   let low = 0, high = arr.length;
   while (low < high) {
      let mid = (low + high) >>> 1;
      if (arr[mid] < val) {
         low = mid + 1;
      }else {
         high = mid
      }
   };
   return low;
};
const insertAt = (arr = [], num) => {
   const position = findIndex(arr, num);
   for(let i = position; typeof arr[i] !== 'undefined'; i++){
      // swapping without using third variable num += arr[i];
      arr[i] = num - arr[i];
      num -= arr[i];
   };
   arr.push(num);
};
insertAt(arr, num);
console.log(arr);

Output

This will produce the following output −

[
   6, 7, 8, 9, 12,
   14, 15, 16, 17, 19,
   20, 22
]
raja
Published on 25-Nov-2020 05:05:28
Advertisements