1-min guide

Sorting and time complexity

Putting jumbled data in order is called “sorting.” Depending on the method (the algorithm), the number of comparisons can differ by orders of magnitude.

Reading time: about 1 min

More in the 5-min version →
Number of items →Comparisons → Bubble sort Quicksort
Double the data, and bubble sort’s effort roughly quadruples. Quicksort’s grows a little over double

Four common sorts

Comparing the number of comparisons

Number of itemsBubble sortQuicksort (average)
1045about 24
1004,950about 650
1,000499,500about 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
  • 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
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 →