diff --git a/src/assets/js/algorithm/sort.js b/src/assets/js/algorithm/sort.js index 8f68d87..6e81fbb 100644 --- a/src/assets/js/algorithm/sort.js +++ b/src/assets/js/algorithm/sort.js @@ -473,6 +473,7 @@ class CountingSort extends Sort { return { name: "计数排序算法", enName: "Counting Sort", + available: true } } @@ -488,8 +489,37 @@ class CountingSort extends Sort { sort(array) { if (array.length == 0) 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 } diff --git a/src/assets/js/algorithm/test.js b/src/assets/js/algorithm/test.js index d1e9b7e..76341f1 100644 --- a/src/assets/js/algorithm/test.js +++ b/src/assets/js/algorithm/test.js @@ -42,6 +42,7 @@ var sortAlgorithm = { selectionSort: new SelectionSort(animation), insertionSort: new InsertionSort(animation), randomQuickSort: new RandomQuickSort(animation), + countingSort: new CountingSort(animation), } // 遍历每一种算法