Skip to content

Commit c419b96

Browse files
authored
Merge pull request #1248 from harshitcompcode/patch-3
Create bucket_sort.js
2 parents f1d9304 + 83cc31a commit c419b96

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

sorting/bucket_sort.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
Here's an implementation of bucket sort in JavaScript:
2+
3+
function bucketSort(arr, numBuckets = 10) {
4+
const n = arr.length;
5+
const buckets = new Array(numBuckets);
6+
7+
// Initialize the buckets
8+
for (let i = 0; i < numBuckets; i++) {
9+
buckets[i] = [];
10+
}
11+
12+
// Distribute the elements into the buckets
13+
for (let i = 0; i < n; i++) {
14+
const bucketIndex = Math.floor(arr[i] * numBuckets);
15+
buckets[bucketIndex].push(arr[i]);
16+
}
17+
18+
// Sort the elements within each bucket
19+
for (let i = 0; i < numBuckets; i++) {
20+
buckets[i].sort((a, b) => a - b);
21+
}
22+
23+
// Concatenate the sorted buckets
24+
let sortedArr = [];
25+
for (let i = 0; i < numBuckets; i++) {
26+
sortedArr = sortedArr.concat(buckets[i]);
27+
}
28+
29+
return sortedArr;
30+
}
31+
32+
33+
The bucketSort function takes an array arr of numbers and an optional parameter numBuckets that specifies the number of buckets to use (default is 10).
34+
The algorithm works by distributing the elements of arr into numBuckets buckets based on their value. Each bucket contains elements within a range of values,
35+
and since the buckets are sorted, the elements within each bucket are sorted as well. Finally, the sorted buckets are concatenated to obtain the final sorted
36+
array.
37+
38+
Note that the performance of bucket sort depends on the distribution of the elements in the input array. If the elements are evenly distributed, bucket sort can achieve a time complexity of O(n), which is faster than many other sorting algorithms. However, if the elements are concentrated in a small range of values, the buckets may become unbalanced and the performance may degrade. Therefore, bucket sort is often used as a sub-routine in other sorting algorithms, or when the distribution of the input is known to be relatively even.

0 commit comments

Comments
 (0)