

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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 ]
- Related Questions & Answers
- Insert into a Sorted Circular Linked List in C++
- Finding desired numbers in a sorted array in JavaScript
- Merging two sorted arrays into one sorted array using JavaScript
- Python program to insert an element into sorted list
- Find missing element in a sorted array of consecutive numbers in C++
- Find missing element in a sorted array of consecutive numbers in Python
- Removing duplicates from a sorted array of literals in JavaScript
- Split number into 4 random numbers in JavaScript
- Algorithm for sorting array of numbers into sets in JavaScript
- How to insert an item into an array at a specific index in javaScript?
- Turning a 2D array into a sparse array of arrays in JavaScript
- Inserting a new interval in a sorted array of intervals in JavaScript
- Insert JSON into a MySQL table?
- Merge two sorted arrays to form a resultant sorted array in JavaScript
- Split number into n length array - JavaScript
Advertisements