NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Bucket Sorting in Data Structure

Bucket sort distributes elements into several ordered buckets based on value ranges, sorts each bucket individually (using insertion sort or another algorithm), and concatenates the buckets. It runs in O(n + k) average time for uniformly distributed data


Theory & Explanation

Bucket Sort: Definition, Stepwise Working, Complexity & Code

1. Definition & Key Characteristics

Bucket Sort is a distribution-based sorting algorithm that divides a range of input values into a finite number of ordered intervals called buckets, places each element into its corresponding bucket, sorts each non-empty bucket individually (commonly using Insertion Sort), and finally concatenates all buckets in order to produce the sorted output.

  • Best Suited for Uniformly Distributed Data: Works fastest when input elements are evenly distributed across a known range (such as floating-point numbers in [0.0, 1.0) or bounded integers).
  • Non-Comparison / Distribution Approach: Groups elements by value range first rather than relying solely on pairwise comparisons across the whole array.
  • Stability: Can be stable if elements are appended to buckets in order and sorted within each bucket using a stable sorting algorithm like Insertion Sort.
  • Space Trade-Off: Requires extra memory O(n + k) for k buckets and the elements stored inside them.

2. How Bucket Sort Works (Step-by-Step Algorithm)

  1. Create Buckets: Initialize k empty buckets (lists/arrays) covering sub-ranges of the input domain.
  2. Scatter (Distribute Elements): For each element x in the input array, compute its bucket index (for example, for values in [0, 1) with k buckets, idx = floor(k x)) and insert x into bucket idx.
  3. Sort Individual Buckets: Sort the elements inside each bucket (typically with Insertion Sort, which is fast on small or nearly uniform buckets).
  4. Gather (Concatenate): Iterate through buckets from index 0 to k - 1 and copy all elements back into the output array in order.

3. Step-by-Step Example & Graphical Representation

Sort arr = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68] (10 elements in [0.0, 1.0)) using 5 buckets covering intervals: Bucket 0: [0.0, 0.2), Bucket 1: [0.2, 0.4), Bucket 2: [0.4, 0.6), Bucket 3: [0.6, 0.8), Bucket 4: [0.8, 1.0):

  • Step 1 — Distribute using bucketIndex = floor(5 x):
    • 0.78 → floor(3.9) = 3; 0.17 → 0; 0.39 → 1; 0.26 → 1; 0.72 → 3;
    • 0.94 → 4; 0.21 → 1; 0.12 → 0; 0.23 → 1; 0.68 → 3.
  • Step 2 — Sort Each Bucket:
    • Bucket 0: [0.17, 0.12] → [0.12, 0.17]
    • Bucket 1: [0.39, 0.26, 0.21, 0.23] → [0.21, 0.23, 0.26, 0.39]
    • Bucket 2: [] (empty)
    • Bucket 3: [0.78, 0.72, 0.68] → [0.68, 0.72, 0.78]
    • Bucket 4: [0.94] → [0.94]
  • Step 3 — Concatenate Buckets 0 to 4: [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94].

Graphical Representation: Stepwise Distribution, Bucket Sorting & Concatenation

Bucket Sort Trace (5 Buckets, idx = floor(5 × x)): Scatter → Sort → Gather
1. Scatter into Buckets
B0 [0.0-0.2): 0.17, 0.12
B1 [0.2-0.4): 0.39, 0.26, 0.21, 0.23
B2 [0.4-0.6): (empty)
B3 [0.6-0.8): 0.78, 0.72, 0.68
B4 [0.8-1.0): 0.94
2. Sort Each Bucket
B0: [0.12, 0.17]
B1: [0.21, 0.23, 0.26, 0.39]
B2: []
B3: [0.68, 0.72, 0.78]
B4: [0.94]
3. Gather (Concatenate)
Join B0 + B1 + B2 + B3 + B4
0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94
Sorted in O(n + k) average time

4. Time & Space Complexity Analysis

Case Condition Time Complexity Exam Note
Best Case Elements evenly spread across buckets Ω(n + k) Each bucket has ~n/k items; small buckets sort quickly
Average Case Uniform distribution across buckets Θ(n + k) (or Θ(n) when k = Θ(n)) Expected cost per bucket is constant when keys are uniformly distributed
Worst Case All elements land in a single bucket O(n2) (if Insertion Sort is used inside bucket) Degrades to the sorting cost of that single bucket (O(n log n) if using Merge/Heap sort inside buckets)

Auxiliary Space Complexity: O(n + k) for k buckets holding n elements.

5. C Program: Bucket Sort (For Floats in [0.0, 1.0))

#include <stdio.h>
#include <stdlib.h>

#define BUCKETS 5

void insertionSortFloat(float arr[], int n) {
    for (int i = 1; i < n; i++) {
        float key = arr[i];
        int j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}

void bucketSort(float arr[], int n) {
    float buckets[BUCKETS][n];
    int counts[BUCKETS] = {0};

    // 1. Distribute elements into buckets
    for (int i = 0; i < n; i++) {
        int idx = (int)(arr[i]  BUCKETS);
        if (idx >= BUCKETS) idx = BUCKETS - 1;
        buckets[idx][counts[idx]++] = arr[i];
    }

    // 2. Sort each bucket and gather back into arr[]
    int k = 0;
    for (int i = 0; i < BUCKETS; i++) {
        if (counts[i] > 0) {
            insertionSortFloat(buckets[i], counts[i]);
            for (int j = 0; j < counts[i]; j++) {
                arr[k++] = buckets[i][j];
            }
        }
    }
}

int main() {
    float arr[] = {0.78f, 0.17f, 0.39f, 0.26f, 0.72f, 0.94f, 0.21f, 0.12f, 0.23f, 0.68f};
    int n = sizeof(arr) / sizeof(arr[0]);

    bucketSort(arr, n);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%.2f ", arr[i]);
    }
    printf("\n");

    return 0;
}

Expected Output (C):

Sorted array: 0.12 0.17 0.21 0.23 0.26 0.39 0.68 0.72 0.78 0.94 

6. Python Program: Bucket Sort

def insertion_sort(sub):
    for i in range(1, len(sub)):
        key = sub[i]
        j = i - 1
        while j >= 0 and sub[j] > key:
            sub[j + 1] = sub[j]
            j -= 1
        sub[j + 1] = key
    return sub


def bucket_sort(arr, num_buckets=5):
    if not arr:
        return []

    buckets = [[] for _ in range(num_buckets)]

    # 1. Scatter elements into buckets (for values in [0.0, 1.0))
    for val in arr:
        idx = min(int(val  num_buckets), num_buckets - 1)
        buckets[idx].append(val)

    # 2. Sort each bucket and gather
    sorted_arr = []
    for bucket in buckets:
        sorted_arr.extend(insertion_sort(bucket))

    return sorted_arr


if __name__ == "__main__":
    data = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]
    print("Original array:", data)
    print("Sorted array:  ", bucket_sort(data, num_buckets=5))

Expected Output (Python):

Original array: [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]
Sorted array:   [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
Advertisement
Advertisement