Knowledge Guide
HomeDSAAdvanced Patterns

Bucket Sort Algorithm

Bucket Sort is a comparison-based sorting algorithm that distributes elements into several 'buckets'. Each bucket is then sorted individually, either using another sorting algorithm or recursively applying the bucket sort. Finally, the sorted buckets are concatenated to form the final sorted array. This algorithm is particularly effective when the input is uniformly distributed over a range.

Bucket Sort works in the following steps:

  1. Distribute Elements into Buckets: Divide the input array into a number of buckets.
  2. Sort Each Bucket: Sort each bucket individually.
  3. Concatenate Buckets: Concatenate the sorted buckets to form the final sorted array.

Bucket Sort can achieve a linear time complexity of in the best case scenario, where the elements are uniformly distributed. However, in the worst case, when all elements fall into the same bucket, the time complexity can degrade to .

Step-by-Step Algorithm for Bucket Sort

  1. Initialize Buckets:

    • Determine the number of buckets: The number of buckets is typically the square root of the number of elements, numBuckets = sqrt(n).
    • Create an array of buckets: Each bucket is an empty list to hold the elements.
  2. Distribute Elements into Buckets:

    • Find the maximum value in the array: This helps in distributing elements uniformly.
    • Calculate the index for each element: For each element num in the array, calculate the bucket index as bucketIndex = (num * numBuckets) / (maxVal + 1).
    • Place each element into its corresponding bucket: Add the element to the list at buckets[bucketIndex].
  3. Sort Each Bucket:

    • For each bucket, sort the elements using a comparison-based sorting algorithm (e.g., Timsort provided by Collections.sort in Java).
  4. Concatenate Buckets:

    • Combine the sorted buckets into the original array.

Algorithm Walkthrough

Input: array1 = {29, 25, 3, 49, 9, 37, 21, 43, 45}

Image
Image
  1. Initialize Buckets:

    • Determine the number of buckets: numBuckets = sqrt(9) ≈ 3.
    • Create an array of 3 empty buckets: buckets = [[], [], []].
  2. Distribute Elements into Buckets:

    • Find the maximum value: maxVal = 49.

    • Calculate the bucket index and place each element into its corresponding bucket:

      • For 29: bucketIndex = (29 * 3) / 50 ≈ 1. Place 29 into buckets[1].
      • For 25: bucketIndex = (25 * 3) / 50 ≈ 1. Place 25 into buckets[1].
      • For 3: bucketIndex = (3 * 3) / 50 ≈ 0. Place 3 into buckets[0].
      • For 49: bucketIndex = (49 * 3) / 50 ≈ 2. Place 49 into buckets[2].
      • For 9: bucketIndex = (9 * 3) / 50 ≈ 0. Place 9 into buckets[0].
      • For 37: bucketIndex = (37 * 3) / 50 ≈ 2. Place 37 into buckets[2].
      • For 21: bucketIndex = (21 * 3) / 50 ≈ 1. Place 21 into buckets[1].
      • For 43: bucketIndex = (43 * 3) / 50 ≈ 2. Place 43 into buckets[2].
      • For 45: bucketIndex = (45 * 3) / 50 ≈ 2. Place 45 into buckets[2].
    • After distribution, buckets look like:

      • buckets[0] = [3, 9]
      • buckets[1] = [29, 25, 21]
      • buckets[2] = [49, 37, 43, 45]
  3. Sort Each Bucket:

    • Sort each bucket individually:
      • buckets[0] becomes [3, 9].
      • buckets[1] becomes [21, 25, 29].
      • buckets[2] becomes [37, 43, 45, 49].
  4. Concatenate Buckets:

    • Combine the sorted buckets into the original array:
      • array = [3, 9, 21, 25, 29, 37, 43, 45, 49].

Code

java
import java.util.ArrayList;
import java.util.Collections;

public class Solution {

    // Function to perform Bucket Sort
    public void bucketSort(int[] array) {
        if (array.length <= 0) {
            return;
        }

        // Step 1: Create buckets
        int numBuckets = (int) Math.sqrt(array.length); // Number of buckets
        ArrayList<Integer>[] buckets = new ArrayList[numBuckets];

        // Initialize buckets
        for (int i = 0; i < numBuckets; i++) {
            buckets[i] = new ArrayList<>();
        }

        // Step 2: Distribute elements into buckets
        int maxVal = getMax(array);
        for (int num : array) {
            int bucketIndex = (num * numBuckets) / (maxVal + 1);
            buckets[bucketIndex].add(num);
        }

        // Step 3: Sort each bucket
        for (ArrayList<Integer> bucket : buckets) {
            Collections.sort(bucket);
        }

        // Step 4: Concatenate buckets
        int index = 0;
        for (ArrayList<Integer> bucket : buckets) {
            for (int num : bucket) {
                array[index++] = num;
            }
        }
    }

    // Helper function to find the maximum value in the array
    private int getMax(int[] array) {
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }
        return max;
    }

    // Main method to test Bucket Sort with 3 examples
    public static void main(String[] args) {
        Solution sol = new Solution();

        // Example 1
        int[] array1 = {29, 25, 3, 49, 9, 37, 21, 43, 45};
        sol.bucketSort(array1);
        System.out.println("Sorted array 1: " + java.util.Arrays.toString(array1));

        // Example 2
        int[] array2 = {78, 17, 39, 26, 72, 94, 21, 12, 23, 68};
        sol.bucketSort(array2);
        System.out.println("Sorted array 2: " + java.util.Arrays.toString(array2));

        // Example 3
        int[] array3 = {4, 3, 2, 1, 0, 9, 8, 7, 6, 5};
        sol.bucketSort(array3);
        System.out.println("Sorted array 3: " + java.util.Arrays.toString(array3));
    }
}

Complexity Analysis for Bucket Sort

Time Complexity

  1. Creating Buckets: Initializing buckets takes time.

  2. Distributing Elements into Buckets: This takes time.

  3. Sorting Each Bucket:

    • If the input elements are uniformly distributed, the number of elements in each bucket is approximately .
    • Sorting each bucket using a comparison-based sort like Timsort (which is used by Collections.sort()) takes time, where k is the number of elements in a bucket.
    • Since there are buckets, the total time for sorting all buckets is .
  4. Concatenating Buckets:

    • Combining the sorted buckets to form the final sorted array takes time.

Overall Time Complexity:

Space Complexity

Overall Space Complexity: , which includes the original array and the buckets.

Real-Time Applications of Bucket Sort

  1. Sorting Floating Point Numbers

    • Application: Bucket Sort is particularly effective for sorting floating point numbers that are uniformly distributed over a range.
    • Example: Sorting grades or percentages in educational institutions.
  2. Data Distribution Analysis

    • Application: When analyzing large datasets, Bucket Sort can be used to categorize and sort data points into different ranges or buckets.
    • Example: Sorting temperature readings or rainfall measurements for climate studies.
  3. Digital Signal Processing

    • Application: In digital signal processing, Bucket Sort can help in sorting and organizing signal data points.
    • Example: Sorting frequency components in a Fast Fourier Transform (FFT) algorithm.
  4. Parallel Processing

    • Application: Bucket Sort is well-suited for parallel processing, where different buckets can be processed and sorted independently.
    • Example: Sorting large datasets in distributed computing environments or multi-core processors.
  5. External Sorting

    • Application: Bucket Sort can be used in external sorting, where data that does not fit into memory is divided into chunks that are sorted independently.
    • Example: Sorting large log files or database records stored on disk.
🤖 Don't fully get this? Learn it with Claude

Stuck on Bucket Sort Algorithm? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Bucket Sort Algorithm** (DSA) and want to truly understand it. Explain Bucket Sort Algorithm from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Bucket Sort Algorithm** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Bucket Sort Algorithm** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Bucket Sort Algorithm** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes