1. Small input
Small arrays need no bucket work.
if (arr.length <= 1) return arrTyporithm · hard
Step 1 of 8 · intro card
Sorting Algorithms
Bucket Sort distributes values into range buckets, sorts each bucket, and concatenates the buckets.
Bucket Sort relies on values being reasonably distributed over a known numeric range.
The min and max values determine how many buckets are needed.
Each input value maps to a bucket based on its distance from min and the bucket size.
Buckets are sorted individually; this version uses Insertion Sort because buckets should be small.
When distribution is good, Bucket Sort can approach linear time; when buckets are uneven, it depends on the inner sort.
Choose a bucket size.
Map values into range buckets.
Sort each bucket locally.
Flatten buckets from low range to high range.
Best when values are evenly distributed.
function bucketSort(arr, bucketSize = 5) {
if (arr.length <= 1) return arr;
const min = Math.min(...arr);
const max = Math.max(...arr);
const bucketCount = Math.floor((max - min) / bucketSize) + 1;
const buckets = Array.from({ length: bucketCount }, () => []);
for (const value of arr) {
const index = Math.floor((value - min) / bucketSize);
buckets[index].push(value);
}
return buckets.flatMap((bucket) => insertionSort(bucket));
}
function insertionSort(bucket) {
for (let i = 1; i < bucket.length; i++) {
const current = bucket[i];
let j = i - 1;
while (j >= 0 && bucket[j] > current) {
bucket[j + 1] = bucket[j];
j--;
}
bucket[j + 1] = current;
}
return bucket;
}Connect each part of the code to the concept before you type.
Small arrays need no bucket work.
if (arr.length <= 1) return arrThe minimum anchors the first bucket.
const min = Math.min(...arr)The maximum helps compute how many buckets are needed.
const max = Math.max(...arr)The value range divided by bucket size determines the number of buckets.
const bucketCount = Math.floor((max - min) / bucketSize) + 1Create a list of empty buckets.
Array.from({ length: bucketCount }, () => [])Shift by min, divide by bucket size, and floor to choose a bucket.
const index = Math.floor((value - min) / bucketSize)Values in the same range go into the same bucket.
buckets[index].push(value)Sort each bucket, then concatenate buckets in order.
return buckets.flatMap((bucket) => insertionSort(bucket))Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
Input[5,1,4,2,8]
n value references in b = 3 range buckets, plus a collection buffer. Sorting inside the buckets uses a fixed-size temporary. The input array is not counted as extra space.
One reusable value slot. Empty until the next operation needs it.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state