Monday, June 24, 2013

JavaScript Binary Insertion Sort

I ported over the binary insertion sort algorithm from this blog post to JavaScript. The two changes I made were that I used Math.floor to truncate the floats when division occurs and replaced memmove() with a for-loop from one of the previous implementations in the post.
function binaryInsertionSort (a)
{
    var i, m;
    var hi, lo, tmp;
    var n = a.length;

    for (i = 1; i < n; i++) {
        lo = 0, hi = i;
        m = Math.floor(i / 2);

        do {
            if (a[i] > a[m]) {
                lo = m + 1;
            } else if (a[i] < a[m]) {
                hi = m;
            } else
                break;

            m = Math.floor(lo + ((hi - lo) / 2));
        } while (lo < hi);
 
        if (m < i) {
            tmp = a[i];
            for (j = i - 1; j >= m; j--)
                a[j + 1] = a[j];
            a[m] = tmp;
        }
    }
    
    return a;
}

//outputs [11, 40, 42, 66, 73, 90]
binaryInsertionSort([66, 73, 42, 40, 90, 11]); 

No comments:

Post a Comment