Created
July 11, 2013 17:13
-
-
Save PatrickJS/5977321 to your computer and use it in GitHub Desktop.
Bubble Sort in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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