Bucket Sort
Distribution sort that distributes elements into buckets, then sorts each bucket individually. Works well when input is uniformly distributed. Combines with insertion sort for bucket sorting.
Visualization
Interactive visualization for Bucket Sort
Bucket Sort Visualization
Interactive visualization with step-by-step execution
Implementation
1function bucketSort(arr: number[], bucketCount: number = 10): number[] {
2 if (arr.length === 0) return [];
3
4 const min = Math.min(...arr);
5 const max = Math.max(...arr);
6 const bucketSize = (max - min) / bucketCount;
7
8 const buckets: number[][] = Array.from({ length: bucketCount }, () => []);
9
10 // Distribute elements into buckets
11 for (const num of arr) {
12 const bucketIndex = Math.min(
13 Math.floor((num - min) / bucketSize),
14 bucketCount - 1
15 );
16 buckets[bucketIndex].push(num);
17 }
18
19 // Sort each bucket and concatenate
20 return buckets.flatMap(bucket =>
21 bucket.sort((a, b) => a - b)
22 );
23}Deep Dive
Theoretical Foundation
Divides array into n buckets. Each bucket is sorted individually using another sorting algorithm. Finally, concatenates all sorted buckets. Performance depends on distribution and bucket sort choice. Best when input uniformly distributed over range.
Complexity
Time
O(n + k)
O(n + k)
O(n²)
Space
O(n + k)
Applications
Use Cases
Related Algorithms
Quicksort
A highly efficient, in-place sorting algorithm that uses divide-and-conquer strategy. Invented by Tony Hoare in 1959, it remains one of the most widely used sorting algorithms due to its excellent average-case performance and cache efficiency.
Merge Sort
A stable, divide-and-conquer sorting algorithm with guaranteed O(n log n) performance.
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. This process is repeated until the entire array is sorted. Named for the way larger elements 'bubble' to the top (end) of the array.
Insertion Sort
Insertion Sort is a simple, intuitive sorting algorithm that builds the final sorted array one element at a time. It works similarly to how people sort playing cards in their hands - picking each card and inserting it into its correct position among the already sorted cards. Despite its O(n²) time complexity, Insertion Sort is efficient for small datasets and nearly sorted arrays, making it practical for real-world applications.