Created
August 17, 2016 21:35
-
-
Save kurtzilla/1fbf8dda3229f806dc217fd93c446d9b to your computer and use it in GitHub Desktop.
A functional explanation of the bubble sort
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
// perform a search bigO(n^2) | |
function bubbleSort(arr) { | |
// loop through every array element: indices: 0 thru (last-1) | |
// note starting i at 1 - we need to be able to decrease the looping iterations and if | |
// we had used a zero index, the loop would not progress correctly | |
// this is because each iteration moves the highest value in the lopped through set | |
// to the last element. So on the next iteration, we can skip examining the last element | |
var iterations = arr.length-1; | |
for(var i=1;i<iterations;i++){ | |
// loop through the elements of the array up to the elements we are know are sorted correctly | |
var counter = 0; | |
while(counter<arr.length - i ){ | |
// examine elements and swap if applicable | |
var tmp = arr[counter]; | |
var next = arr[counter+1]; | |
if(tmp > next){ | |
arr[counter] = next; | |
arr[counter+1] = tmp; | |
} | |
// increase the loop counter for this particular iteration | |
counter++; | |
} | |
} | |
// return our result | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment