Selection, Bubble & Shaker Sorts

Selection Sort

Selection Sort makes n passes through the data, each time selecting which one is the largest. When it finishes a pass, it swaps that one with the last element, so it’s at the end. That element is then retired, so that it won’t move anymore. It then starts a new pass, finding the second-largest element and swapping it into the second-last position. It keeps doing this until it’s finished.

This sorting algorithm will do (½n² - ½n) comparisons (at most). However, it only does (n-1) (or fewer) swaps.

Bubble Sort

Bubble Sort looks at each adjacent pair in turn, swapping them so that those two are in order. The largest element rises to the top during each pass, like a bubble. After the last swap, the element is retired.

Like selection sort, bubble sort will do no more than (½n² - ½n) comparisons. Unlike selection sort, it might swap each time it compares, so the maximum number of swaps is also (½n² - ½n)!

You can also optimize bubble sort, by allowing multiple retirements on each pass. Count how many non-swaps there are at the end, and that’s the number of extra elements you can retire.

Here it is, working on semi-sorted data:

Shaker Sort

Shaker Sort is just a slight variation of bubble sort. The passes switch directions, first doing first-to-last, and then doing last-to-first. The number of comparisons and swaps doesn’t change, but getting the least elements out of the way can speed it up significantly!

You can also optimize shaker sort in the same way as bubble sort, retiring multiple elements at once:

On semi-sorted data:

Comparing the Three

Here are all three of the algorithms shown at once.

And here are the three, acting on semi-sorted data.

More Advanced Sorting Algorithms

There are other sorting algorithms, beyond those we’ll show in this class. Here are several of them: