[javascript] Efficient way to insert a number into a sorted array of numbers?

Here is my function, uses binary search to find item and then inserts appropriately:

_x000D_
_x000D_
function binaryInsert(val, arr){_x000D_
    let mid, _x000D_
    len=arr.length,_x000D_
    start=0,_x000D_
    end=len-1;_x000D_
    while(start <= end){_x000D_
        mid = Math.floor((end + start)/2);_x000D_
        if(val <= arr[mid]){_x000D_
            if(val >= arr[mid-1]){_x000D_
                arr.splice(mid,0,val);_x000D_
                break;_x000D_
            }_x000D_
            end = mid-1;_x000D_
        }else{_x000D_
            if(val <= arr[mid+1]){_x000D_
                arr.splice(mid+1,0,val);_x000D_
                break;_x000D_
            }_x000D_
            start = mid+1;_x000D_
        }_x000D_
    }_x000D_
    return arr;_x000D_
}_x000D_
_x000D_
console.log(binaryInsert(16, [_x000D_
    5,   6,  14,  19, 23, 44,_x000D_
   35,  51,  86,  68, 63, 71,_x000D_
   87, 117_x000D_
 ]));
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to algorithm

How can I tell if an algorithm is efficient? Find the smallest positive integer that does not occur in a given sequence Efficiently getting all divisors of a given number Peak signal detection in realtime timeseries data What is the optimal algorithm for the game 2048? How can I sort a std::map first by value, then by key? Finding square root without using sqrt function? Fastest way to flatten / un-flatten nested JSON objects Mergesort with Python Find common substring between two strings

Examples related to sorting

Sort Array of object by object field in Angular 6 Sorting a list with stream.sorted() in Java How to sort dates from Oldest to Newest in Excel? how to sort pandas dataframe from one column Reverse a comparator in Java 8 Find the unique values in a column and then sort them pandas groupby sort within groups pandas groupby sort descending order Efficiently sorting a numpy array in descending order? Swift: Sort array of objects alphabetically