From 3a37e4e18f5f0541f3c1ec5f7949fef1b23df839 Mon Sep 17 00:00:00 2001 From: kevinbzhang Date: Mon, 8 Aug 2022 16:19:46 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=20=E8=AE=A1=E6=95=B0?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E7=AE=97=E6=B3=95=EF=BC=88=E5=BC=80=E5=8F=91?= =?UTF-8?q?=E4=B8=AD=EF=BC=8C=E4=B8=8D=E8=A6=81=E5=90=88=E5=88=86=E6=94=AF?= =?UTF-8?q?=EF=BC=89=EF=BC=9B=E5=8A=A8=E7=94=BB=E5=B1=95=E7=A4=BA=E4=B8=8D?= =?UTF-8?q?=E5=A5=BD=E5=B1=95=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/assets/js/algorithm/sort.js | 34 +++++++++++++++++++++++++++++++-- src/assets/js/algorithm/test.js | 1 + 2 files changed, 33 insertions(+), 2 deletions(-) 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), } // 遍历每一种算法