javascriptarraysbinary-search

Javascript Binary Search/Insertion Performance


function binarySearch(value)
{
    var startIndex = 0,
        stopIndex = words.length - 1,
        middle = Math.floor((stopIndex + startIndex) / 2);

    while (words[middle] != value && startIndex < stopIndex) {
        // adjust search area
        if (value < words[middle]) {
            stopIndex = middle - 1;
        } else if (value > words[middle]) {
            startIndex = middle + 1;
        }

        // recalculate middle
        middle = Math.floor((stopIndex + startIndex) / 2);
    }
}

I am making a large list of words in the format of an array:

e.g. ["a","ab","abc","b"]

In alphabetical order. The problem I'm having is modifying my binary search algorithm to add the word in the correct place and then update?

Whats the best way performance-wise to add a word into an ordered array? And why is it the best way to do it?


Solution

  • The best way is to use trees instead, since for an array such an operation is likely to have linear algorithmic complexity.

    If you'd like to stick with the arrays, I suggest that you use the splice method for insertion.