We saw that CocktailSort improve a bit for turtles (i.e. small values near to the end of the array), but it is still possible to achieve better. ComboSort comes down to providing them a short cut: instead of comparing adjacent values, we compare values separated by a gap bigger than 1. That way, turtles will traverse gap cells at each traversal. Naturally, we have to apply the algorithm with decreasing gaps, and finish with gap=1 to ensure that the array is correctly sorted afterward. Choosing the right gap and how to decrease it is a difficult question, but in practice, dividing it by 1.3 after each traversal leads to good performance. Here is the corresponding pseudo-code:
gap = len; do if gap>1 then gap = gap / 1.3 i = O while i+gap < len do: if i and i+gap must be swapped, do it increase i by one while the gap is bigger than 1 or the last traversal swapped at least one pair[!scala]
One tricky part is that we want to divide gap, that is an integer (of type Int), by 1.3, that is a Double. The type system of scala won't let us do this, because such discrepancy usually denotes a programmer error. As this is not an error this time, we have to convert gap to Double for the time of the operation, and then convert the result back to Int to store it into gap. This should be written this way:
gap = (gap.asInstanceOf[Double] / 1.3).asInstanceOf[Int]
This is rather verbose, but actually, this notation is not very complex. And remember that the type checker is your friend. It's picky and sometimes annoying (as on this one), but it often catches weird bugs that would have been a pain to debug if not catch by the type checker. And since the Scala's authors are pragmatic, the previous expression can be simplified:
gap = (gap.toDouble / 1.3).toInt
toDouble
and toInt
are just shortcuts for the
corresponding expressions asInstanceOf[Double]
and
asInstanceOf[Int]
. It's not very generic, but it's very handy.
This algorithm was invented by Wlodek Dobosiewicz in 1980, and later rediscovered and popularized by Stephen Lacey and Richard Box, who described it in Byte Magazine in April 1991.