Skip to content

Instantly share code, notes, and snippets.

@kurtzilla
Created August 17, 2016 21:35
Show Gist options
  • Save kurtzilla/1fbf8dda3229f806dc217fd93c446d9b to your computer and use it in GitHub Desktop.
Save kurtzilla/1fbf8dda3229f806dc217fd93c446d9b to your computer and use it in GitHub Desktop.
A functional explanation of the bubble sort
// 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