Cocktail Shaker Sort would like a drink. A strong one, if you please.

The father of four rambunctious children and husband to the always-working Heap Sort, “Shaky” (a loving nickname for him which is never said to his face) is a stay-at-home dad who absolutely adores his children but just wants some alone time, is that so much to ask?

The problem is that, when he gets his alone time (rare as it is), he would greatly prefer to curl up with his beloved Heapy, but failing that, he’ll make a stiff drink that the rest of the family can’t be in the same room as. Not that he minds. Heapy is his best friend, his companion, his true love, but the rest of her family he could take or leave. Nevertheless, his kids love him, and the family has accepted him, even if he hasn’t quite gotten around to feeling the same way.

The Rundown

Algorithm

  1. PASS THROUGH the collection from left-to-right.

  2. DURING that pass, SELECT the highest encountered value.

  3. DEPOSIT that value at the end of the considered range.

  4. DECREASE the end of the considered range by 1.

  5. PASS THROUGH the collection from right-to-left.

  6. DURING that pass, SELECT the lowest encountered value.

  7. DEPOSIT that value at the beginning of the considered range.

  8. INCREASE the start of the considered range by 1.

  9. GO TO 1, CONTINUE until the range is 0.

Get “The Catch Block”, My Weekly Newsletter!

Plus my eBook “The Daily Design Pattern”, early access, new posts in your inbox, and more for becoming a paid subscriber.

Go!

I will not spam, sell your email, etc.

Visualization

Lucky for us, Cocktail Shaker sort is an easy sort to understand. On each pass through the collection, it either finds the highest or lowest encountered value (depending on pass direction) and deposits that value at the beginning or end of the considered range. In fact, Cocktail Shaker sort is really just Bubble Sort but in both directions.

#exchange sorts #algorithms

Cocktail Shaker Sort - The Sorting Algorithm Family Reunion
1.55 GEEK