- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- Finding desired numbers in a sorted array in JavaScript
- Insert into a Sorted Circular Linked List in C++
- Merging two sorted arrays into one sorted array using JavaScript
- Python program to insert an element into sorted list
- Removing duplicates from a sorted array of literals in JavaScript
- Merge two sorted arrays to form a resultant sorted array in JavaScript
- Inserting a new interval in a sorted array of intervals in JavaScript
- Find missing element in a sorted array of consecutive numbers in Python
- Find missing element in a sorted array of consecutive numbers in C++
- Algorithm for sorting array of numbers into sets in JavaScript
- Split number into 4 random numbers in JavaScript
- Return a sorted array in lexicographical order in JavaScript
- Searching in a sorted 2-D array in JavaScript
- Split number into n length array - JavaScript
- Turning a 2D array into a sparse array of arrays in JavaScript

Advertisements