TRT
Sign in
mediumCoreLeetCode#merge sort#quick sort#random pivot

Sort an array

Sort an array of integers in O(n log n) without the built-in sort: implement merge sort, then quick sort with a random pivot, and compare.

The Runtime Theory Team1 min read
Taught inMerge sortPro — members onlySplit the array in half, sort each half, merge the two sorted halves. Every level of splitting costs O(n) and there are log n levels, so merge sort is O(n log n) on every input, and it is stable.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [5, 2, 3, 1]

out[1, 2, 3, 5]

innums = [5, 1, 1, 2, 0, 0]

out[0, 0, 1, 1, 2, 5]

innums = [2, 2, 2, 2, 2]

out[2, 2, 2, 2, 2]

Sort an array of up to 50,000 integers in ascending order without using a built-in sort, in O(n log n) time.

Before you code

The judge includes inputs designed to break naive quick sort: already sorted arrays and arrays full of duplicates. Decide how your implementation survives each.

Hints

  1. Merge sort passes every case: split, sort both halves, merge into a buffer. Allocate one buffer up front instead of one per call.
  2. Quick sort needs a random (or median-of-three) pivot to survive sorted input.
  3. Quick sort with a two-way partition is slow on [2, 2, 2, …]. A three-way partition puts all elements equal to the pivot in the middle and never touches them again.
  4. Time both on 50,000 random values and on 50,000 copies of one value.

Production & complexity notes

When solving Sort an array on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Merge sort to reinforce the underlying pattern.

What it practices

Implementing and comparing the two O(n log n) sorts, from Merge sort and Quick sort and partitioning.

Not started

Sign in to save your learning progress.

Sign in to save