Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit 3065c25

Browse files
authored
Add bucket sort algorithm in JavaScript (#913)
1 parent 1be2095 commit 3065c25

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Javascript/Algorithms/bucket-sort.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
const arr = [32, 6, 34, 4, 78, 1, 6767, 4, 65, 34, 879, 7];
2+
const bucketSort = arr => {
3+
if (arr.length === 0) {
4+
return arr;
5+
}
6+
let i,
7+
minValue = arr[0],
8+
maxValue = arr[0],
9+
bucketSize = 5;
10+
arr.forEach(function (currentVal) {
11+
if (currentVal < minValue) {
12+
minValue = currentVal;
13+
} else if (currentVal > maxValue) {
14+
maxValue = currentVal;
15+
}
16+
})
17+
let bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;
18+
let allBuckets = new Array(bucketCount);
19+
for (i = 0; i < allBuckets.length; i++) {
20+
allBuckets[i] = [];
21+
}
22+
arr.forEach(function (currentVal) {
23+
allBuckets[Math.floor((currentVal - minValue) / bucketSize)].push(currentVal);
24+
});
25+
arr.length = 0;
26+
allBuckets.forEach(function(bucket) {
27+
insertion(bucket);
28+
bucket.forEach(function (element) {
29+
arr.push(element)
30+
});
31+
});
32+
return arr;
33+
}
34+
const insertion = arr => {
35+
let length = arr.length;
36+
let i, j;
37+
for(i = 1; i < length; i++) {
38+
let temp = arr[i];
39+
for(j = i - 1; j >= 0 && arr[j] > temp; j--) {
40+
arr[j+1] = arr[j];
41+
}
42+
arr[j+1] = temp;
43+
}
44+
return arr;
45+
};
46+
console.log(bucketSort(arr));

0 commit comments

Comments
 (0)