Last Updated: June 30, 2016
·
1.039K
· 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);

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside