
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Insert a Number into a Sorted Array of Numbers in JavaScript
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 ]
Advertisements