-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathbucketSort.js
61 lines (50 loc) · 1.31 KB
/
bucketSort.js
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
// InsertionSort to be used within bucket sort
function insertionSort(array) {
var length = array.length;
for(var i = 1; i < length; i++) {
var temp = array[i];
for(var j = i - 1; j >= 0 && array[j] > temp; j--) {
array[j+1] = array[j];
}
array[j+1] = temp;
}
return array;
}
// Implement bucket sort
function bucketSort(array, bucketSize) {
if (array.length === 0) {
return array;
}
// Declaring vars
var i,
minValue = array[0],
maxValue = array[0],
bucketSize = bucketSize || 5;
// Setting min and max values
array.forEach(function (currentVal) {
if (currentVal < minValue) {
minValue = currentVal;
} else if (currentVal > maxValue) {
maxValue = currentVal;
}
})
// Initializing buckets
var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;
var allBuckets = new Array(bucketCount);
for (i = 0; i < allBuckets.length; i++) {
allBuckets[i] = [];
}
// Pushing values to buckets
array.forEach(function (currentVal) {
allBuckets[Math.floor((currentVal - minValue) / bucketSize)].push(currentVal);
});
// Sorting buckets
array.length = 0;
allBuckets.forEach(function(bucket) {
insertionSort(bucket);
bucket.forEach(function (element) {
array.push(element)
});
});
return array;
}