Sorting Exercises: Practice Problems (with Solutions)
Time to practice sorting. Solve each problem yourself first — write the code, trace a small example by hand, and reason about its time and space complexity. Only then open the answer sheet. Every View answer link jumps to a full, multi-language solution on the sorting solutions page.
How to practice: Set a timer (15–20 min per problem). If you’re stuck, re-read the relevant page — the sorting introduction, an algorithm page, or built-in sorting — before peeking.
Warm-ups
Q1. Implement insertion sort. Sort an integer array ascending, in place, using insertion sort. State its best, average, and worst-case time complexity.
Q2. Sort numbers descending (mind the comparator). Sort an integer array in descending order using your language’s built-in sort. In JavaScript, explain why arr.sort() with no comparator gives the wrong answer for numbers.
Core problems
Q3. Sort pairs by score, ties by name. Given a list of (name, score) records, sort by score descending; when scores tie, order by name ascending. Use a stable, multi-key sort.
Q4. Merge two sorted arrays. Given two arrays that are each already sorted ascending, return one merged sorted array in O(n + m) time. (This is the merge step of merge sort.)
Q5. Counting sort for a bounded range. Sort an array whose values are integers in [0, k] in O(n + k) time without comparing elements.
Challenge
Q6. Kth largest element. Return the k-th largest element of an unsorted array. A sort gives O(n log n); can you describe an average O(n) approach?
Q7. Sort colors (Dutch national flag). Given an array containing only 0, 1, and 2, sort it in a single pass with O(1) extra space — no counting-then-rewriting in two passes.
Done? Review every solution on the sorting answer sheet — even the ones you solved, since there’s often a cleaner approach. Then continue to Searching.