Skip to content

Commit fcffdac

Browse files
committed
add javascript bucketSort
1 parent 63e2dd2 commit fcffdac

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

javascript/13_sorts/bucketSort.js

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// 思路:
2+
// 将数组中的数据,按桶进行划分,将相邻的数据划分在同一个桶中
3+
// 每个桶用插入排序算法(或者快速排序)进行排序
4+
// 最后整合每个桶中的数据
5+
6+
function bucketSort(array, bucketSize = 5) {
7+
if (array.length < 2) {
8+
return array
9+
}
10+
const buckets = createBuckets(array, bucketSize)
11+
return sortBuckets(buckets)
12+
}
13+
14+
function createBuckets(array, bucketSize) {
15+
let minValue = array[0]
16+
let maxValue = array[0]
17+
// 遍历数组,找到数组最小值与数组最大值
18+
for (let i = 1; i < array.length; i++) {
19+
if (array[i] < minValue) {
20+
minValue = array[i]
21+
} else if (array[i] > maxValue) {
22+
maxValue = array[i]
23+
}
24+
}
25+
// 根据最小值、最大值、桶的大小,计算得到桶的个数
26+
const bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1
27+
// 建立一个二维数组,将桶放入buckets中
28+
const buckets = []
29+
for (let i = 0; i < bucketCount; i++) {
30+
buckets[i] = []
31+
}
32+
// 计算每一个值应该放在哪一个桶中
33+
for (let i = 0; i < array.length; i++) {
34+
const bucketIndex = Math.floor((array[i] - minValue) / bucketSize)
35+
buckets[bucketIndex].push(array[i])
36+
}
37+
return buckets
38+
}
39+
40+
function sortBuckets(buckets) {
41+
const sortedArray = []
42+
for (let i = 0; i < buckets.length; i++) {
43+
if (buckets[i] != null) {
44+
insertionSort(buckets[i])
45+
sortedArray.push(...buckets[i])
46+
}
47+
}
48+
return sortedArray
49+
}
50+
51+
// 插入排序
52+
function insertionSort(array) {
53+
const { length } = array
54+
if (length <= 1) return
55+
56+
for (let i = 1; i < length; i++) {
57+
let value = array[i]
58+
let j = i - 1
59+
60+
while (j >= 0) {
61+
if (array[j] > value) {
62+
array[j + 1] = array[j] // 移动
63+
j--
64+
} else {
65+
break
66+
}
67+
}
68+
array[j + 1] = value // 插入数据
69+
}
70+
}

0 commit comments

Comments
 (0)