Courses / Computer Science I
Algorithmics

Sorting Strategies

Computer Science I 370 words Free to read

Putting Things in Order

Sorting arranges a collection into order, and it is one of the most studied problems in computing because so much else (searching, deduplication, grouping) becomes easy once data is sorted.

The simple sorts are quadratic, O(n2)O(n^2), and easy to understand:

The efficient sorts are O(nlogn)O(n \log n) and are what real systems use for large data:

A key property is stability: a stable sort preserves the relative order of elements that compare equal. This matters when sorting by one field while wanting ties broken by a previous order (sort by last name, keeping first-name order within ties). Merge sort is stable; the usual quicksort is not.

There is a proven lower bound: any comparison-based sort needs at least Ω(nlogn)\Omega(n \log n) comparisons in the worst case — so O(nlogn)O(n \log n) is the best a general comparison sort can do.

Common pitfall: assuming the "best" sort is always the fastest asymptotic one. For small or nearly-sorted inputs, a simple O(n2)O(n^2) insertion sort can beat an O(nlogn)O(n \log n) sort because of lower constant overhead — which is why real library sorts switch to insertion sort for small sub-arrays. Match the sort to the input.

A merge-sort recursion tree: a list splitting into halves down log n levels, then accent merge-arrows combining sorted runs back up, with a side note that each of the log n levels does O(n) work.

merge sort=O(nlogn)\text{merge sort} = O(n \log n)

Sorting Strategies

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

11practice questions
2interactive scenes
Start Computer Science I free

Algorithmics