Skip to content

Commit e0e4e68

Browse files
Merge pull request #407 from milesmao233/master
add javascript bucketSort and countingSort
2 parents 65ac826 + b362685 commit e0e4e68

File tree

2 files changed

+108
-0
lines changed

2 files changed

+108
-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+
}

javascript/13_sorts/countingSort.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const countingSort = array => {
2+
if (array.length <= 1) return
3+
4+
const max = findMaxValue(array)
5+
const counts = new Array(max + 1)
6+
7+
// 计算每个元素的个数,放入到counts桶中
8+
// counts下标是元素,值是元素个数
9+
array.forEach(element => {
10+
if (!counts[element]) {
11+
counts[element] = 0
12+
}
13+
counts[element]++
14+
})
15+
16+
// counts下标是元素,值是元素个数
17+
// 例如: array: [6, 4, 3, 1], counts: [empty, 1, empty, 1, 1, empty, 1]
18+
// i是元素, count是元素个数
19+
let sortedIndex = 0
20+
counts.forEach((count, i) => {
21+
while (count > 0) {
22+
array[sortedIndex] = i
23+
sortedIndex++
24+
count--
25+
}
26+
})
27+
// return array
28+
}
29+
30+
function findMaxValue(array) {
31+
let max = array[0]
32+
for (let i = 1; i < array.length; i++) {
33+
if (array[i] > max) {
34+
max = array[i]
35+
}
36+
}
37+
return max
38+
}

0 commit comments

Comments
 (0)