Cocktail Sort

Monday, May 31, 2010 by gradbot

Cocktail sort is similar to bubble sort except it reverses directions when it reaches the end of the list instead of starting from the beginning. Wikipedia on cocktail sort.








algorithms.sort.cocktail = 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;
}
}

if (!found)
break;

for (var i = length - 1; i > 1; i--) {
if (predicate(array, i, i - 1)) {
array.swap(i, i - 1);
found = true;
}
}
}
};


Filed under , , , having  

0 comments: