c2cedge
Data Structures & Algorithms · C — Searching & Sorting

Sorting Algorithms

You rarely write a sort in a real job, but tests love their complexities, trade-offs and stability. Know them cold.

Test weight: Very highTime / question: 1–2 minDifficulty: Easy–Medium

Sorting is the most-tested topic in placement DSA — not to write from scratch, but to compare. You should instantly recall each algorithm's time and space complexity, whether it is stable, and when each is the right choice.

Three speeds of sorting

The simple sorts (bubble, selection, insertion) are O(n²). The efficient comparison sorts (merge, heap) are O(n log n) guaranteed. Quicksort averages O(n log n) but degrades to O(n²) on bad pivots.

AlgorithmBestAverageWorstSpaceStable
BubbleO(n)O(n^2)O(n^2)O(1)Yes
SelectionO(n^2)O(n^2)O(n^2)O(1)No
InsertionO(n)O(n^2)O(n^2)O(1)Yes
MergeO(n log n)O(n log n)O(n log n)O(n)Yes
QuickO(n log n)O(n log n)O(n^2)O(log n)No
HeapO(n log n)O(n log n)O(n log n)O(1)No
⚡ The edge
  • Memorise the table: simple sorts are O(n²); merge and heap are O(n log n) guaranteed; quicksort is O(n log n) on average but O(n²) on a sorted input with a naive pivot.
  • When a problem says values are small integers in a known range, a non-comparison sort (counting / radix) can hit O(n).
Worked example
One pass of bubble sort on [5, 1, 4, 2]. What is the array after the first pass?
  1. Compare and swap adjacent out-of-order pairs, left to right.
  2. 5>1 swap -> [1,5,4,2]; 5>4 swap -> [1,4,5,2]; 5>2 swap -> [1,4,2,5].
  3. After one pass the largest element (5) has 'bubbled' to the end.
Worked example
Why is merge sort O(n log n)?
  1. It splits the array in half repeatedly, giving about log n levels of division.
  2. At each level, merging all the pieces touches every element once — O(n) work per level.
  3. log n levels times O(n) per level gives O(n log n).
⚠ Watch out
  • Stability matters when sorting by one key while preserving another's order — merge and insertion are stable; quick and heap are not.
  • Quicksort's worst case O(n²) happens on already-sorted input with a poor pivot — use a random or median pivot.
  • Counting/radix sort beats O(n log n) only for bounded integer ranges, and uses extra space.
Practice this — take a timed mock →
1,300+ questions, scored, with a weak-area report.
Know who's ready. Not who finished.
HomeLibraryPrivacyTerms