All topics
37

Sorting by partitioning around a pivot

Tier 1Locked

Where it runs

1. The problem

Merge sort gave you O(n log n) time. It cuts the list in half without looking at the values. It does most of its work later, when it merges the halves. Another method reaches the same speed: it does most of the work before the split.

Pick one item and call it the pivot. Split the others into two groups: the numbers smaller than the pivot and the numbers not smaller than it. Now the pivot is in its final place: everything on its left is smaller, everything on its right is equal or bigger. You never have to move it again.

That one move is the whole idea. Make it, then make the same move in each group.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

Recognise it

Fast sort (merge / quick)

Say these words and it is this pattern

  • sort an array of real size (thousands+)
  • need O(n log n) guaranteed or expected
  • sort as a subroutine before another algorithm (two pointers, greedy, sweep)
  • stability required (merge sort) or in-place expected (quicksort)
  • just "sort this" with no small-n or special-key hint

Looks similar, isn't

n up to 1e6 gives O(n log n). Merge sort needs O(n) extra memory, quick sort needs O(log n).

On LeetCode

Problems that split an array around a pivot value, or find the kth largest item without sorting everything. One partition puts the pivot in its final place.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy