Definition. Quadratic sorting methods

[comp1110-1X]

We demonstrated two sorting algorithms in the lecture:

  • Selection sort: We divide the array into an "unsorted zone" and a "sorted zone". The sorted zone begins empty at the start of the array, and the unsorted zone begins by occupying the whole array. Each loop iteration, we look through the unsorted zone, find the minimum, and swap it with the first element of the unsorted zone (right next to the sorted zone). This means that the sorted zone can be expanded by one element. Repeat until the unsorted zone is of size zero.
  • Bubble sort: Here, the "sorted zone" grows from the end of the array rather than the beginning. Loop through the unsorted zone comparing adjacent elements. If they are not in order, swap them. This will result in the highest element reaching the top. This means we can increase the size of the sorted zone. Repeat until all sorted.

    If we go through the unsorted zone without doing any swaps, we can immediately stop — the array is sorted. This is called an early exit trick.

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.

bars magnifying-glass caret-down plus minus arrow-right xmark