Skip to main content

DSAPath9 mincore

Sorting

Sorting rearranges items into order by key. It is a base operation for search, deduplication, joins, ranking, interval algorithms, and many divide-and-conquer algorithms.

Why This Matters

Sorting makes order usable. Once data is sorted, binary search, duplicate removal, interval merging, sweep-line algorithms, and many database-style joins become simpler.

Core Idea

Comparison sorting can only learn order by comparing pairs. General comparison sorting has an Ω(nlogn)\Omega(n \log n) lower bound in the worst case.

AlgorithmTypical role
bubble sortteaching baseline, not production
insertion sortsmall or nearly sorted arrays
merge sortstable O(nlogn)O(n \log n) sorting
quicksortfast average-case in-place sorting

Worked example: sorting meeting intervals by start time turns overlap detection into a single left-to-right scan.

Common Mistakes

  • Treating all O(nlogn)O(n \log n) sorts as identical. Stability, memory, constants, and input distribution matter.
  • Using bubble sort outside teaching.
  • Forgetting that non-comparison sorts need assumptions about keys.

Exercises

  • Identify whether a sort must be stable for sorting records by two keys.
  • Explain why sorted data makes binary search possible.
  • Compare merge sort and quicksort on memory use.

Next Topics

References

  • Cormen, Leiserson, Rivest, Stein. Introduction to Algorithms (4th ed., 2022). Ch. 2, 6, 7, 8.
  • Knuth. The Art of Computer Programming, Volume 3: Sorting and Searching (2nd ed., 1998).