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:
- Distribute Elements into Buckets: Divide the input array into a number of buckets.
- Sort Each Bucket: Sort each bucket individually.
- Concatenate Buckets: Concatenate the sorted buckets to form the final sorted array.
Bucket Sort can achieve a linear time complexity of
Step-by-Step Algorithm for Bucket Sort
-
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.
- Determine the number of buckets: The number of buckets is typically the square root of the number of elements,
-
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
numin the array, calculate the bucket index asbucketIndex = (num * numBuckets) / (maxVal + 1). - Place each element into its corresponding bucket: Add the element to the list at
buckets[bucketIndex].
-
Sort Each Bucket:
- For each bucket, sort the elements using a comparison-based sorting algorithm (e.g., Timsort provided by
Collections.sortin Java).
- For each bucket, sort the elements using a comparison-based sorting algorithm (e.g., Timsort provided by
-
Concatenate Buckets:
- Combine the sorted buckets into the original array.
Algorithm Walkthrough
Input: array1 = {29, 25, 3, 49, 9, 37, 21, 43, 45}
-
Initialize Buckets:
- Determine the number of buckets:
numBuckets = sqrt(9) ≈ 3. - Create an array of 3 empty buckets:
buckets = [[], [], []].
- Determine the number of buckets:
-
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. Place29intobuckets[1]. - For
25:bucketIndex = (25 * 3) / 50 ≈ 1. Place25intobuckets[1]. - For
3:bucketIndex = (3 * 3) / 50 ≈ 0. Place3intobuckets[0]. - For
49:bucketIndex = (49 * 3) / 50 ≈ 2. Place49intobuckets[2]. - For
9:bucketIndex = (9 * 3) / 50 ≈ 0. Place9intobuckets[0]. - For
37:bucketIndex = (37 * 3) / 50 ≈ 2. Place37intobuckets[2]. - For
21:bucketIndex = (21 * 3) / 50 ≈ 1. Place21intobuckets[1]. - For
43:bucketIndex = (43 * 3) / 50 ≈ 2. Place43intobuckets[2]. - For
45:bucketIndex = (45 * 3) / 50 ≈ 2. Place45intobuckets[2].
- For
-
After distribution,
bucketslook like:buckets[0] = [3, 9]buckets[1] = [29, 25, 21]buckets[2] = [49, 37, 43, 45]
-
-
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].
- Sort each bucket individually:
-
Concatenate Buckets:
- Combine the sorted buckets into the original array:
array = [3, 9, 21, 25, 29, 37, 43, 45, 49].
- Combine the sorted buckets into the original array:
Code
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
-
Creating Buckets: Initializing buckets takes
time. -
Distributing Elements into Buckets: This takes
time. -
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()) takestime, where k is the number of elements in a bucket. - Since there are
buckets, the total time for sorting all buckets is .
- If the input elements are uniformly distributed, the number of elements in each bucket is approximately
-
Concatenating Buckets:
- Combining the sorted buckets to form the final sorted array takes
time.
- Combining the sorted buckets to form the final sorted array takes
Overall Time Complexity:
- Best Case:
, where k is the number of elements in a bucket. If the elements are uniformly distributed and k is small, this simplifies to . - Worst Case:
, considering a fairly uniform distribution of elements.
Space Complexity
- The space complexity for Bucket Sort includes the space for the buckets and the additional space used by the sorting algorithm.
- Buckets require
space. - The sorting algorithm within each bucket can use
additional space, but since k is small compared to n, this is negligible.
Overall Space Complexity:
Real-Time Applications of Bucket Sort
-
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.
-
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.
-
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.
-
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.
-
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.
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.
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.
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.
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.