forked from vJechsmayr/JavaScriptAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBucketSort.js
More file actions
63 lines (51 loc) · 1.42 KB
/
BucketSort.js
File metadata and controls
63 lines (51 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//Language: Javascript
//Author: Maria Luize
//Github: https://github.com/MariaLuize
function insertSort(arr) {
const len = arr.length;
for(let i = 1; i < len; i++) {
let temp = arr[i];
for(let j = i - 1; j >= 0 && arr[j] > temp; j--) {
arr[j+1] = arr[j];
}
arr[j+1] = temp;
}
return arr;
}
// Bucket sort itself
function bucketSort(arr, bucketSize) {
if (arr.length === 0) {
return arr;
}
var i,
minValue = arr[0],
maxValue = arr[0],
bucketSize = bucketSize || 5;
// Setting min and max values
arr.forEach(function (currentVal) {
if (currentVal < minValue) {
minValue = currentVal;
} else if (currentVal > maxValue) {
maxValue = currentVal;
}
})
// Initializing buckets
const bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;
let allBuckets = new Array(bucketCount);
for (i = 0; i < allBuckets.length; i++) {
allBuckets[i] = [];
}
// Pushing values
arr.forEach((currentVal) => {
allBuckets[Math.floor((currentVal - minValue) / bucketSize)].push(currentVal);
});
// Sorting buckets
arr.length = 0;
allBuckets.forEach((bucket) => {
insertionSort(bucket);
bucket.forEach((element) =>{
arr.push(element)
});
});
return arr;
}