Python 3D Academyবাংলা

Quickselect and bucket sort: when sorting everything is too much

🌍 In real life. To find the student of middle height, a teacher doesn't have to line up the whole class in order. Pick someone, send the shorter ones left and the taller ones right, and count: if 14 went left, the middle (15th) student is the one picked. If not, only one side needs another look.

And a tea stall that wants its two best sellers doesn't sort every order: it counts them, puts each item into a pile by how many times it was ordered, and reads the piles from the biggest count down.

The idea in one sentence: quickselect partitions around a pivot exactly as quick sort does, but then follows only the side that holds position k, so on average it does about 2n comparisons instead of n log n; bucket sort puts each value into a bucket chosen from the value itself (here, its count), so reading the buckets in order needs no comparisons at all.

Its words:

  • k-th smallest: the item that would sit at index k after sorting; the median is k = n // 2
  • partition: the step from Lesson 45.2: smaller items to the left of the pivot, the rest to the right, the pivot in its final place
  • bucket: a list holding every value that maps to one key, like "ordered 3 times"
  • expected time: the average over the random pivot choices

Step by step, quickselect. Partition once. The pivot lands at its final index store:

  1. store == k: the pivot is the answer.
  2. store < k: the answer is to the right; drop the left side.
  3. store > k: the answer is to the left; drop the right side.

Here is one partition. The pivot 3 lands at index 2, so it is the 3rd smallest, and if we wanted the 4th smallest (k = 3), only the four items on the right still matter:

Why quickselect is O(n) on average. A random pivot splits the list somewhere in the middle half at least half of the time, so the part that is left shrinks by a steady fraction: n + 3n/4 + (3/4)²n + … stays below 4n, and on average it is about 2n to 3n comparisons. Quick sort keeps both halves, which is where its log n comes from. The worst case, a terrible pivot every time, is still O(n²), which is why the pivot is random. In Python, heapq.nsmallest(k + 1, nums)[-1] (O(n log k), Lesson 49.3) or sorted(nums)[k] (O(n log n)) are fine for small inputs.

Bucket sort for "the k most frequent" (LeetCode 347). No item can be seen more than n times, so counts are whole numbers from 1 to n: make n + 1 buckets and drop each item into buckets[count]. Reading from bucket n downwards meets the items in order of frequency. Counting is O(n), the buckets are O(n), and reading is O(n): O(n) in all, against O(n log n) for sorting the counts. It works because the keys (counts) are small whole numbers, like counting sort in Lesson 45.3.

import random


def quickselect(nums, k):                   # the k-th smallest, counting from 0
    lo, hi = 0, len(nums) - 1
    while True:
        p = random.randint(lo, hi)          # a random pivot, moved to the end
        nums[p], nums[hi] = nums[hi], nums[p]
        pivot, store = nums[hi], lo
        for j in range(lo, hi):
            if nums[j] < pivot:
                nums[store], nums[j] = nums[j], nums[store]
                store += 1
        nums[store], nums[hi] = nums[hi], nums[store]
        if store == k:
            return nums[store]
        if store < k:
            lo = store + 1                  # the answer is on the right
        else:
            hi = store - 1                  # the answer is on the left


heights = [150, 138, 162, 145, 171, 140, 155]
print(quickselect(heights[:], 3), sorted(heights)[3])        # the median
print(quickselect([7, 2, 9, 4, 1, 8, 3], 0), quickselect([5], 0))


from collections import Counter


def top_k_frequent(items, k):
    count = Counter(items)
    buckets = [[] for _ in range(len(items) + 1)]   # buckets[c]: items seen c times
    for item, c in count.items():
        buckets[c].append(item)
    out = []
    for c in range(len(items), 0, -1):              # the most frequent first
        for item in buckets[c]:
            out.append(item)
            if len(out) == k:
                return out
    return out


print(top_k_frequent([1, 1, 1, 2, 2, 3], 2))
quickselect changes the list it is given, so the heights are passed as a copy.

Mistakes and edge cases.

  • Following both sides. Recursing into both halves is quick sort again: O(n log n). Keep only the side with index k.
  • A fixed pivot. Always taking the last item makes an already sorted list the worst case, O(n²). Pick the pivot at random.
  • Mixing up k. Decide whether k counts from 0 or 1. The k-th largest is the (n − k)-th smallest counting from 0.
  • Partitioning the wrong way round. nums[j] > pivot puts the big items on the left, so the search finds the k-th largest instead.
  • Buckets by value with huge values. Bucket sort needs small keys. Counts are at most n, so they are fine; bucketing raw numbers up to a billion is not.
  • Ties in the answer. If two items share a count, which comes first depends on their order in the bucket; say how ties should be broken if it matters.

Quiz

  1. After one partition the pivot lands at index 5, and you want k = 2. What next?

    • Search only the left part, indexes up to 4
    • Search only the right part
    • Return the pivot
  2. Why is quickselect O(n) on average while quick sort is O(n log n)?

    • It keeps only one side after each partition, so the work shrinks geometrically
    • It never compares items
    • It uses a heap
  3. What does this print?

    from collections import Counter
    
    
    def top_k_frequent(items, k):
        count = Counter(items)
        buckets = [[] for _ in range(len(items) + 1)]   # buckets[c]: items seen c times
        for item, c in count.items():
            buckets[c].append(item)
        out = []
        for c in range(len(items), 0, -1):              # the most frequent first
            for item in buckets[c]:
                out.append(item)
                if len(out) == k:
                    return out
        return out
    
    
    print(top_k_frequent(["a", "b", "a", "c", "b", "a"], 2))
  4. quickselect([7, 2, 9, 4, 1, 8, 3], 1) should give 2, the second smallest, but gives 8. Which line is wrong?

    def quickselect(nums, k):
        lo, hi = 0, len(nums) - 1
        while True:
            pivot, store = nums[hi], lo
            for j in range(lo, hi):
                if nums[j] > pivot:
                    nums[store], nums[j] = nums[j], nums[store]
                    store += 1
            nums[store], nums[hi] = nums[hi], nums[store]
            if store == k:
                return nums[store]
            if store < k:
                lo = store + 1
            else:
                hi = store - 1

Coding tasks

  1. Write kth_largest(nums, k) (k counts from 1: k = 1 is the largest) with quickselect and a random pivot. Don't sort the list.

  2. Write top_k_frequent(items, k) with buckets indexed by count (O(n), no sorting of the counts), and return the answer sorted, so ties don't matter.