We demonstrated two sorting algorithms in the lecture:
I briefly mentioned another one at the start of the workshop:
- Insertion sort: The most popular of these three, and somewhat similar to selection sort, in that the
sorted zone begins empty and grows from the left. Instead of finding the minimum, however, we take the first element from
the unsorted zone and remember it (call it
X) and shift everything greater than X in the sorted zone to the right one spot. Then we place X in the slot left over.
These algorithms are called "quadratic" because they take a quadratic amount of key operations (in terms of the size of the array), in this case comparisons and moves/swaps to perform.
While insertion sort is generally the most popular of the three, each of them have their own advantages, depending on your particular situation. On arrays:
- Selection sort minimizes the number of times you have to move an array element.
- Bubble sort only swaps adjacent elements and has an easy way to exit early on sorted arrays.
- Insertion sort can minimize the number of comparisons that you do (these can become expensive on more complex data types).
Which of these you actually get depends on the particulars of your implementation, and minor variations (say starting from the other direction) can make a huge difference for certain scenarios.