Skip to the solution
MediumDSA10 min read

Compare common sorting algorithms.

219 views

The problem

Question presented to candidate: "Walk me through the common sorting algorithms — bubble, selection, insertion, merge, quick and heap sort. How do they compare, and which would you pick in different situations? Feel free to show code in Python."

What a strong answer should cover:

  • Compares on the right axes: best, average and worst time, extra space, stability and adaptivity.
  • Correct complexities: the three simple sorts are O(n²); merge and heap sort are O(n log n) always; quicksort is O(n log n) average but O(n²) worst case.
  • Explains why quicksort is still popular (in place, cache-friendly, good pivots make the worst case unlikely) and what introsort or random pivots do.
  • Mentions the n log n lower bound for comparison sorts and when counting or radix sort can beat it.
  • Knows that Python's sorted/list.sort is a stable Timsort-family sort, that sort() returns None, and that key= is preferred over a comparator.
  • Picks an algorithm from the input shape: nearly sorted, needs stability, tight memory, linked list, small integer keys.

Clarifying questions expected:

  • How big is the input, and is it nearly sorted already?
  • Do equal keys need to keep their original order (stability)?
  • Is extra memory a constraint, and is the data an array or a linked list?

Code / implementation expected: Optional — a short Python implementation of one O(n²) and one O(n log n) sort is a good bonus; the comparison and the choice matter more.

  • sorting

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read · 14 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonComparison counts: the three simple sorts
PythonComparison counts: merge, quick and heap sort
PythonStability: which sorts keep equal keys in order

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 113 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

What is the sliding window technique?

Continue