Last Updated: June 30, 2016
·
795
· b-rucel

JS bubble sort

/**
* Swaps two values in an array.
* @param {Array} items The array containing the items.
* @param {int} firstIndex Index of first item to swap.
* @param {int} secondIndex Index of second item to swap.
* @return {void}
*/
function swap(items, firstIndex, secondIndex){
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}

/**
* A bubble sort implementation in JavaScript. The array
* is sorted in-place.
* @param {Array} items An array of items to sort.
* @return {Array} The sorted array.
*/
function bubbleSort(items){

var len = items.length,
    i, j, stop;

for (i=0; i < len; i++){
    for (j=0, stop=len-i; j < stop; j++){
        if (items[j] > items[j+1]){
            swap(items, j, j+1);
        }
    }
}

return items;

}

// create an array with random values
var randomArray = Array.apply(null, Array(5)).map(function (_, i) {return i;}).sort(function() {
return .5 - Math.random();
});

bubbleSort(randomArray);