mirror of
https://gitee.com/coder-xiaomo/algorithm-visualization
synced 2025-01-10 19:58:18 +08:00
实现 计数排序算法(开发中,不要合分支);动画展示不好展示
This commit is contained in:
parent
7c62e215c5
commit
3a37e4e18f
@ -473,6 +473,7 @@ class CountingSort extends Sort {
|
|||||||
return {
|
return {
|
||||||
name: "计数排序算法",
|
name: "计数排序算法",
|
||||||
enName: "Counting Sort",
|
enName: "Counting Sort",
|
||||||
|
available: true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -488,8 +489,37 @@ class CountingSort extends Sort {
|
|||||||
sort(array) {
|
sort(array) {
|
||||||
if (array.length == 0)
|
if (array.length == 0)
|
||||||
return array
|
return array
|
||||||
// todo
|
|
||||||
console.log("尚未实现")
|
// 下面这个算法有问题
|
||||||
|
|
||||||
|
console.log("array: ", array)
|
||||||
|
// 检查 array 是否符合要求
|
||||||
|
if (array.some(item => typeof item !== 'number')) {
|
||||||
|
console.error("数组中的元素必须是数字")
|
||||||
|
return
|
||||||
|
} else if (array.some(item => item < 0)) {
|
||||||
|
console.error("数组中的元素必须是非负数")
|
||||||
|
return
|
||||||
|
} else if (array.some(item => item % 1 !== 0)) {
|
||||||
|
console.error("数组中的元素必须是整数")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let maxValue = Math.max(...array)
|
||||||
|
console.log(maxValue)
|
||||||
|
let count = new Array(maxValue).fill(0);
|
||||||
|
for (let i = 0; i < array.length; i++) {
|
||||||
|
count[array[i]]++
|
||||||
|
}
|
||||||
|
|
||||||
|
let index = 0
|
||||||
|
for (let i = 0; i < count.length; i++) {
|
||||||
|
while (count[i] > 0) {
|
||||||
|
array[index++] = i
|
||||||
|
count[i]--
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return array
|
return array
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -42,6 +42,7 @@ var sortAlgorithm = {
|
|||||||
selectionSort: new SelectionSort(animation),
|
selectionSort: new SelectionSort(animation),
|
||||||
insertionSort: new InsertionSort(animation),
|
insertionSort: new InsertionSort(animation),
|
||||||
randomQuickSort: new RandomQuickSort(animation),
|
randomQuickSort: new RandomQuickSort(animation),
|
||||||
|
countingSort: new CountingSort(animation),
|
||||||
}
|
}
|
||||||
|
|
||||||
// 遍历每一种算法
|
// 遍历每一种算法
|
||||||
|
Loading…
Reference in New Issue
Block a user