Bubble Sort

Monday, May 31, 2010 by gradbot

Inspired be Wikipedia's algorithm pages I decided to recreate their animations using JavaSrcipt and HTML5 canvas elements. IE 8 does not support canvas however new versions of all other modern browsers do. Mozilla Firefox, Google Chrome, Safari, and Opera.

Bubble sort works by looking at ever element in a list that is to be sorted and swapping adjacent pairs that are out of order. If it makes it to the end of the list without swapping any elements then it stops and the list is in order. If not then it starts at the beginning again. Wikipedia on Bubble Sort.

algorithms.sort.bubble = function(array, predicate){
var found = true;
var length = array.length;
while (found) {
found = false;
for (var i = 0; i < length - 1; i++) {
if (!predicate(array, i, i + 1)) {
array.swap(i, i + 1);
found = true;

Filed under , , , having