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.
PASS THROUGH the collection from left-to-right.
DURING that pass, SELECT the highest encountered value.
DEPOSIT that value at the end of the considered range.
DECREASE the end of the considered range by 1.
PASS THROUGH the collection from right-to-left.
DURING that pass, SELECT the lowest encountered value.
DEPOSIT that value at the beginning of the considered range.
INCREASE the start of the considered range by 1.
GO TO 1, CONTINUE until the range is 0.
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.
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