Bucket sort

Scatter values into a handful of buckets by value range, sort each small bucket, then read the buckets back in order.

Time O(n + k) averageSpace O(n + k)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Bucket sort divides the value range into a handful of buckets, drops each element into the bucket matching its value, then sorts each bucket (which is small, so any simple sort works) and concatenates the buckets in order. When values are spread evenly across the range, each bucket holds roughly n/k elements, so the small per-bucket sorts plus one linear distribution pass add up to close to linear time overall.

Code

public static int[] BucketSort(int[] a) {
    int min = a.Min(), max = a.Max();
    const int bucketCount = 5;
    var buckets = new List<int>[bucketCount];
    for (int i = 0; i < bucketCount; i++) buckets[i] = new List<int>();
    foreach (int x in a) {
        int idx = (int)((long)(x - min) * bucketCount / (max - min + 1));
        buckets[idx].Add(x);
    }
    var result = new List<int>();
    foreach (var bucket in buckets) {
        bucket.Sort();
        result.AddRange(bucket);
    }
    return result.ToArray();
}
static int[] bucketSort(int[] a) {
    int min = Arrays.stream(a).min().getAsInt(), max = Arrays.stream(a).max().getAsInt();
    final int bucketCount = 5;
    List<List<Integer>> buckets = new ArrayList<>();
    for (int i = 0; i < bucketCount; i++) buckets.add(new ArrayList<>());
    for (int x : a) {
        int idx = (int) ((long) (x - min) * bucketCount / (max - min + 1));
        buckets.get(idx).add(x);
    }
    List<Integer> result = new ArrayList<>();
    for (List<Integer> bucket : buckets) {
        Collections.sort(bucket);
        result.addAll(bucket);
    }
    return result.stream().mapToInt(Integer::intValue).toArray();
}
vector<int> bucketSort(const vector<int>& a) {
    int mn = *min_element(a.begin(), a.end()), mx = *max_element(a.begin(), a.end());
    const int bucketCount = 5;
    vector<vector<int>> buckets(bucketCount);
    for (int x : a) {
        int idx = (int)((long long)(x - mn) * bucketCount / (mx - mn + 1));
        buckets[idx].push_back(x);
    }
    vector<int> result;
    for (auto& bucket : buckets) {
        sort(bucket.begin(), bucket.end());
        result.insert(result.end(), bucket.begin(), bucket.end());
    }
    return result;
}
def bucket_sort(a: list[int]) -> list[int]:
    lo, hi = min(a), max(a)
    bucket_count = 5
    buckets = [[] for _ in range(bucket_count)]
    for x in a:
        idx = (x - lo) * bucket_count // (hi - lo + 1)
        buckets[idx].append(x)
    result = []
    for bucket in buckets:
        bucket.sort()
        result.extend(bucket)
    return result

Tips

In the .NET library

Dictionary and HashSet lean on the same idea for O(1) average lookups: bucket by hash code instead of by value range, then only compare within the matching bucket.