Skip to content

Commit 7b82729

Browse files
authored
Merge pull request TheAlgorithms#64 from KuLi/bucket_sort
Implemented bucket sort algorithm
2 parents 9f7639e + 9cd9b16 commit 7b82729

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Sorts/bucketSort.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the
3+
elements of an array into a number of buckets. Each bucket is then sorted individually, either using
4+
a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a
5+
distribution sort, and is a cousin of radix sort in the most to least significant digit flavour.
6+
Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons
7+
and therefore can also be considered a comparison sort algorithm. The computational complexity estimates
8+
involve the number of buckets.
9+
10+
Time Complexity of Solution:
11+
Best Case O(n); Average Case O(n); Worst Case O(n)
12+
13+
*/
14+
function bucketSort(list, size){
15+
16+
if(undefined === size){
17+
size = 5;
18+
}
19+
if(list.length === 0){
20+
return list;
21+
}
22+
let min = list[0];
23+
let max = list[0];
24+
// find min and max
25+
for(let iList = 0; iList < list.length; iList++){
26+
27+
if(list[iList] < min){
28+
min = list[iList];
29+
} else if(list[iList] > max){
30+
max = list[iList];
31+
}
32+
}
33+
// how many buckets we need
34+
let count = Math.floor((max - min) / size) + 1;
35+
36+
// create buckets
37+
let buckets = [];
38+
for(let iCount = 0; iCount < count; iCount++){
39+
buckets.push([]);
40+
}
41+
42+
// bucket fill
43+
for(let iBucket = 0; iBucket < list.length; iBucket++){
44+
let key = Math.floor((list[iBucket] - min) / size);
45+
buckets[key].push(list[iBucket])
46+
}
47+
let sorted = [];
48+
// now sort every bucket and merge it to the sorted list
49+
for(let iBucket = 0; iBucket < buckets.length; iBucket++){
50+
let arr = buckets[iBucket].sort();
51+
for(let iSorted = 0; iSorted < arr.length; iSorted++){
52+
sorted.push(arr[iSorted]);
53+
}
54+
}
55+
return sorted;
56+
}
57+
let arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14];
58+
//Array before Sort
59+
console.log(arrOrignal);
60+
arrSorted = bucketSort(arrOrignal);
61+
//Array after sort
62+
console.log(arrSorted);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy