Odd-even Sort

Tuesday, June 1, 2010 by gradbot

Odd-even sort is another bubble sort variant and is similar to cocktail sort since it makes alternating passes. Instead of changing directions like cocktail, it tests all the even elements in one pass and then all the odd elements in the next. Wikipedia on Odd-even sort.








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

if (!found)
break;

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


Filed under , , , having  

0 comments: