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.

Approach: Binary Search with In-Place Insertion

The solution uses binary search to find the correct insertion position, then shifts elements using a swapping technique to maintain order without extra space.

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

[
   6,  7,  8,  9, 12,
  14, 15, 16, 17, 19,
  20, 22
]

How It Works

The algorithm works in two phases:

1. Binary Search: The findIndex function uses binary search to find the correct insertion position in O(log n) time.

2. In-Place Shifting: Starting from the insertion position, elements are shifted right using a clever swapping technique that doesn't require a temporary variable.

Alternative Approach: Using splice()

For a simpler solution, JavaScript's splice() method can insert at any position:

const arr2 = [6, 7, 8, 9, 12, 14, 16, 17, 19, 20, 22];
const num2 = 15;

const insertWithSplice = (arr, num) => {
    let position = 0;
    while (position < arr.length && arr[position] < num) {
        position++;
    }
    arr.splice(position, 0, num);
};

insertWithSplice(arr2, num2);
console.log(arr2);

Output

[
   6,  7,  8,  9, 12,
  14, 15, 16, 17, 19,
  20, 22
]

Comparison

Method Time Complexity Space Complexity Readability
Binary Search + Swapping O(log n + n) O(1) Complex
Linear Search + splice() O(n) O(1) Simple

Conclusion

Both methods insert numbers into sorted arrays in-place. The binary search approach is more efficient for finding position, while splice() offers better readability for most practical use cases.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements