Bucket Sort (also known as bin sort) is a non-comparison-based sorting algorithm that distributes elements into a number of buckets, sorts each bucket individually (usually using another algorithm like Insertion Sort), and then concatenates the results to form the final sorted array.
It is particularly useful when:
| Case | Time Complexity |
|---|---|
| Best Case | O(n + k) |
| Average | O(n + k) |
| Worst Case | O(n²) |
n = number of elementsk = number of bucketsimport java.util.*;
public class BucketSortExample {
public static void bucketSort(float[] arr) {
int n = arr.length;
if (n <= 0) return;
// Step 1: Create empty buckets
@SuppressWarnings("unchecked")
List<Float>[] buckets = new List[n];
for (int i = 0; i < n; i++) {
buckets[i] = new ArrayList<>();
}
// Step 2: Distribute elements into buckets
for (int i = 0; i < n; i++) {
int bucketIndex = (int)(arr[i] * n);
buckets[bucketIndex].add(arr[i]);
}
// Step 3: Sort each bucket
for (int i = 0; i < n; i++) {
Collections.sort(buckets[i]); // could use Insertion Sort
}
// Step 4: Concatenate all buckets into arr[]
int index = 0;
for (int i = 0; i < n; i++) {
for (float value : buckets[i]) {
arr[index++] = value;
}
}
}
public static void printArray(float[] arr) {
for (float value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
public static void main(String[] args) {
float[] arr = {0.42f, 0.32f, 0.33f, 0.52f, 0.37f, 0.47f, 0.51f};
System.out.println("Original array:");
printArray(arr);
bucketSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}
Original array:
0.42 0.32 0.33 0.52 0.37 0.47 0.51
Sorted array:
0.32 0.33 0.37 0.42 0.47 0.51 0.52
Given array:
[0.42, 0.32, 0.33, 0.52, 0.37, 0.47, 0.51]
Create 7 buckets (same as array length):
buckets[0], buckets[1], ..., buckets[6]
Calculate bucket index using:index = (int)(value * n)
Buckets:
buckets[2] → [0.42, 0.32, 0.33, 0.37]
buckets[3] → [0.52, 0.47, 0.51]
Sort values inside each bucket:
Final sorted array:
[0.32, 0.33, 0.37, 0.42, 0.47, 0.51, 0.52]
[0, 1).