PERF Merge/Bubble Sort in JS

performance testing it and stuff

by Christopher Stephens

HTML

<div id="logger"></div>

CSS

.title {
    font-weight:bold;
    margin-top:15px;
}

JavaScript

// merge sort

// I'm using a closure/module here so that I can declare merge once and not evertime I call the internal sort
var mergeSort = (function () {
    var merge = function (sortedA, sortedB) {
        var toReturn = [];
        var itA = 0,
            itB = 0,
            Alength = sortedA.length,
            Blength = sortedB.length;
        while (itA < Alength && itB < Blength) {
            if (sortedB[itB] < sortedA[itA]) {
                toReturn.push(sortedB[itB++]);
            } else {
                toReturn.push(sortedA[itA++]);
            }
        }
        toReturn = toReturn.concat(sortedB.slice(itB)).concat(sortedA.slice(itA));
        return toReturn;
    };

    var sort = function (toSort) {
        var arlength = toSort.length;
        var midpoint = Math.round(arlength / 2);

        if (toSort.length > 1) {
            // just here to illistrate the step, these should be remove or renamed and moved to the top of the function
            // MEMOP - slicing creates new arrays, performign this in place would be lighter
            var A = toSort.slice(0, midpoint);
            var B = toSort.slice(midpoint, arlength);
            return merge(sort(A), sort(B));
        }
        return toSort;
    };

    return sort;
})();
var bubbleSort = (function () {
    var swaps = 0;
    var swap = function (arr, s, e) {
        swaps++;
        var temp = arr[s];
        arr[s] = arr[e];
        arr[e] = temp;
    };
    var sort = function (toSort) {
        var passes = 0;
        var i1 = 0;
        var i2;
        var pointer = 0;
        var l = toSort.length;
        for (; i1 < l; i1++) {
            pointer = 0;
            var remainderLe = l - i1;
            for (i2=pointer; i2 < remainderLe; i2++) {
                if (toSort[i2] > toSort[i2 + 1]) {
                    swap(toSort, i2, i2 + 1);
                }
                passes++;
                pointer++;
            }
            
            if(swaps===0)
           ...