-
Notifications
You must be signed in to change notification settings - Fork 17
/
bucketsort.js
53 lines (44 loc) · 1 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
<script>
// Javascript program to sort an array
// using bucket sort
// Function to sort arr[] of size n
// using bucket sort
function bucketSort(arr,n)
{
if (n <= 0)
return;
// 1) Create n empty buckets
let buckets = new Array(n);
for (let i = 0; i < n; i++)
{
buckets[i] = [];
}
// 2) Put array elements in different buckets
for (let i = 0; i < n; i++) {
let idx = arr[i] * n;
buckets[Math.floor(idx)].push(arr[i]);
}
// 3) Sort individual buckets
for (let i = 0; i < n; i++) {
buckets[i].sort(function(a,b){return a-b;});
}
// 4) Concatenate all buckets into arr[]
let index = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < buckets[i].length; j++) {
arr[index++] = buckets[i][j];
}
}
}
// Driver code
let arr = [0.897, 0.565,
0.656, 0.1234,
0.665, 0.3434];
let n = arr.length;
bucketSort(arr, n);
document.write("Sorted array is <br>");
for (let el of arr.values()) {
document.write(el + " ");
}
// This code is contributed by unknown2108
</script>