Skip to content

Instantly share code, notes, and snippets.

@PatrickJS
Created July 11, 2013 17:13
Show Gist options
  • Save PatrickJS/5977321 to your computer and use it in GitHub Desktop.
Save PatrickJS/5977321 to your computer and use it in GitHub Desktop.
Bubble Sort in javascript
var bubbleSort = function(array) {
if (array.constructor !== Array) throw 'not an Array';
do {
var somethingWasSwapped = false;
// go through and...
for(var i = 0, ii = array.length; i < ii; i++) {
// if necessary
if (array[i] > array[i + 1]) {
// swap the two indices
somethingWasSwapped = true;
var temp = array[i+1];
array[i+1] = array[i];
array[i] = temp;
}
}
} while(somethingWasSwapped);
return array;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment