Skip to content

Cocktail shaker sort

ordering

Level 1 of 3

Also called Shaker sort and Bidirectional bubble sort.

fresh numbers

The test's questions that a run answers, asked again on new numbers whenever you like. The answer, its working and the reason for every other choice come from cocktail shaker sort's own run on the numbers shown.

choose one

question 1

Cocktail shaker sort works on 3, 6, 2, 5, 1, 4. What is the row after its first two walks, one right and one back left?

362514
the answer, and why

the answer is A

Walk 1 carries the 6 to the end, leaving 3, 2, 5, 1, 4, 6. Walk 2 goes left from the 4, and the 1 swaps past the 5, the 2 and the 3. The 5 lands beside the 4 only after walk 2 has passed places 4 and 5, so the 5 and the 4 stay the wrong way round.

362514start325146walk 15 pairs compared132546walk 24 pairs compared123456walk 33 pairs compared123456walk 42 pairs, no swapone walkin place for good
3, 6, 2, 5, 1, 4, walk by walk.

if you chose another

  • That is the row after walk 1 only.
  • That is two walks to the right, as bubble sort makes them.
  • That is the row after walk 3, which sorts it.

new numbers

question 2

How many comparisons does cocktail shaker sort make, from start to finish, on 5, 1, 4, 3, 6, 2?

514362
the answer, and why

the answer is A

The four walks compare 5, 4, 3 and 2 pairs. Walk 3 leaves the row in order, but only walk 4, swapping nothing, stops the sort. 5 + 4 + 3 + 2 = 14.

514362start143526walk 15 pairs compared124356walk 24 pairs compared123456walk 33 pairs compared123456walk 42 pairs, no swapone walkin place for good
5, 1, 4, 3, 6, 2, walk by walk.

if you chose another

  • That is bubble sort's count on this row.
  • That counts the swaps, one for each wrong pair.
  • That stops after walk 3, when the row is first in order, but walk 4 still runs to find no swap.

new numbers

question 3

Cocktail shaker sort works on each of these rows of 1 to 5. On which does it make the most swaps?

the answer, and why

the answer is A

Its swaps are the row's wrong pairs. The 5 stands before all 4 smaller numbers, and no other pair is wrong, so 4 swaps, all in walk 1.

51234start4 wrong pairs15234swap 13 wrong pairs12534swap 22 wrong pairs12354swap 31 wrong pair12345swap 4no wrong pairsa wrong pair, bigger before smallerjust swappedthe pair it mended
5, 1, 2, 3, 4, swap by swap.

if you chose another

  • 3 and 1, 3 and 2, and 5 and 4 are wrong, so 3 swaps.
  • 2 and 1, and 4 and 3, are wrong, so 2 swaps.
  • 3 and 2, and 5 and 4, are wrong, so 2 swaps.

new numbers