Four common sorts
- Bubble sort: compare neighbors and swap them if they’re out of order. Repeat from one end many times. Easy to understand, but slow
- Selection sort: find the smallest of the rest and swap it to the front. Few swaps
- Insertion sort: like a hand of cards, slip each one into its correct place. Fast if the data is almost sorted
- Quicksort: pick one value as a pivot, split into a “smaller group” and a “larger group,” and split each the same way again. Very fast on average
Comparing the number of comparisons
| Number of items | Bubble sort | Quicksort (average) |
|---|---|---|
| 10 | 45 | about 24 |
| 100 | 4,950 | about 650 |
| 1,000 | 499,500 | about 11,000 |
Bubble sort makes n×(n−1)÷2 comparisons for n items. How this effort grows is called “time complexity,” written O(n²) (“order n squared”). Quicksort is O(n log n) on average.
How the FE exam asks it
Exams often ask about complexity in the form “if the data grows 10 times, about how many times longer does processing take?” For O(n²), about 100 times; for O(n log n), a bit over 10 times.
Summary
Go further: 5-min deep diveSorting in depth: complexity, stable sorts and binary searchHow to read big-O notation, average vs. worst case, what a “stable sort” means, and why sorted data is faster to search.Read the 5-min version →
- The sorting method changes the number of comparisons by orders of magnitude
- Bubble sort is O(n²); quicksort is O(n log n) on average
- The more data, the wider the gap between algorithms