Algorithms · Visualized

Random: Randomized Quickselect

Randomized Algorithms

Randomness as a tool — shuffles, sampling, and probabilistic selection.

Finds the k-th smallest (or largest) element in an unsorted array without fully sorting it, using the same partitioning idea as Quick Sort but only recursing into the one side that contains the target rank. Time: O(n) average, O(n²) — extremely unlikely with random pivots, unlike deterministic pivot choices worst; space: O(log n) — recursion stack on average.

Big-O: Expected-case guarantees with simple implementations.

Randomized Quickselect

Randomized Algorithms

Finds the k-th smallest (or largest) element in an unsorted array without fully sorting it, using the same partitioning idea as Quick Sort but only recursing into the one side that contains the target rank. Choosing the pivot randomly avoids the worst-case O(n²) behavior that a fixed pivot choice can trigger on adversarial or already-sorted input.

How Randomized Quickselect Works

  1. Pick a pivot element at random from the current portion of the array (this randomization is the key difference from plain Quickselect).
  2. Partition the array around this pivot, just like Quick Sort: smaller elements go left, larger elements go right, and the pivot lands in its final sorted position.
  3. Compare the pivot's final position to the target rank k.
  4. If the pivot's position equals k, you've found the answer — return it immediately.
  5. If k is smaller, recurse only into the left partition; if k is larger, recurse only into the right partition — never both, which is what makes this faster than a full sort.

Randomized Quickselect Worked Example

Input: {array: [7, 10, 4, 3, 20, 15], k: 3}

Looking for the 3rd smallest element. Random pivot chosen, say 10. Partition around 10: smaller elements [7,4,3] go left, larger [20,15] go right, pivot 10 lands at index3 (0-indexed), meaning it's the 4th smallest. Since we want the 3rd smallest (index2), recurse only into the left partition [7,4,3]. Partition again with a new random pivot; eventually converges on the 3rd smallest value: 7.

Random: Randomized QuickselectO(n) expected
Find the k-th smallest via a random pivot.
7
0
10
1
4
2
3
3
20
4
15
5
target3
Step 1 / 22
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Randomized Quickselect: find the 3-th smallest element (0-indexed) in expected O(n) time.
Python · Randomized Algorithms in Code
import random

def quickselect(arr, k):
    # kth smallest (0-indexed)
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        r = arr[lo:hi + 1]
        pivot = r[random.randrange(len(r))]
        # 3-way partition
        less, equal, greater = [], [], []
        for v in r:
            if v < pivot: less.append(v)
            elif v == pivot: equal.append(v)
            else: greater.append(v)
        if k < len(less):
            arr = less; hi = len(arr) - 1; lo = 0
        elif k < len(less) + len(equal):
            return pivot
        else:
            k -= len(less) + len(equal)
            arr = greater; hi = len(arr) - 1; lo = 0

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Randomized Quickselect Time & Space Complexity

BestO(n)
AverageO(n)
WorstO(n²) — extremely unlikely with random pivots, unlike deterministic pivot choices
SpaceO(log n) — recursion stack on average

When to Use Randomized Quickselect

  • Finding medians, percentiles, or top-k elements without the overhead of a full sort.
  • Used internally by many statistics libraries for fast order-statistic queries.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.