MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / bucketSort

Function bucketSort

Sorts/BucketSort.js:20–60  ·  view source on GitHub ↗
(list, size)

Source from the content-addressed store, hash-verified

18 * @return {number[]} An array of numbers sorted in increasing order.
19 */
20export function bucketSort(list, size) {
21 if (undefined === size) {
22 size = 5
23 }
24 if (list.length === 0) {
25 return list
26 }
27 let min = list[0]
28 let max = list[0]
29 // find min and max
30 for (let iList = 0; iList < list.length; iList++) {
31 if (list[iList] < min) {
32 min = list[iList]
33 } else if (list[iList] > max) {
34 max = list[iList]
35 }
36 }
37 // how many buckets we need
38 const count = Math.floor((max - min) / size) + 1
39
40 // create buckets
41 const buckets = []
42 for (let iCount = 0; iCount < count; iCount++) {
43 buckets.push([])
44 }
45
46 // bucket fill
47 for (let iBucket = 0; iBucket < list.length; iBucket++) {
48 const key = Math.floor((list[iBucket] - min) / size)
49 buckets[key].push(list[iBucket])
50 }
51 const sorted = []
52 // now sort every bucket and merge it to the sorted list
53 for (let iBucket = 0; iBucket < buckets.length; iBucket++) {
54 const arr = buckets[iBucket].sort((a, b) => a - b)
55 for (let iSorted = 0; iSorted < arr.length; iSorted++) {
56 sorted.push(arr[iSorted])
57 }
58 }
59 return sorted
60}

Callers 1

BucketSort.test.jsFile · 0.90

Calls 1

pushMethod · 0.45

Tested by

no test coverage detected