From 00f6a80ab185fb1f532af1e9261059dcf49a004c Mon Sep 17 00:00:00 2001 From: yigencong Date: Wed, 28 Feb 2024 13:04:04 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=BF=AB=E9=80=9F=E6=8E=92=E5=BA=8F?= =?UTF-8?q?=E7=9A=84=E5=BA=94=E7=94=A8=EF=BC=8Ctopk=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sort/practice.mjs | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 sort/practice.mjs diff --git a/sort/practice.mjs b/sort/practice.mjs new file mode 100644 index 0000000..0df5f47 --- /dev/null +++ b/sort/practice.mjs @@ -0,0 +1,53 @@ +/** + * + * @param {number[]} arr - 需要操作的数组 + * @param {number} k - 需要找的多少个数 + */ +function topK(arr, k) { + if (k > arr.length) { + throw new Error(`数组的长度必须大于${k}`); + } + let low = 0; + let high = arr.length - 1; + let pivot = partition(arr, low, high); + while (pivot !== k - 1) { // 如果k等于pivot-1说明就找到了 + if (pivot > k - 1) { + high = pivot - 1; + pivot = partition(arr, low, high); + } + if (pivot < k - 1) { + low = pivot + 1; + pivot = partition(arr, low, high); + } + } + return arr.slice(0, k); +} + +/** + * @description 使用经典的挖坑法 + * @param {number[]} 要分解的数组 + * @param {*} low 开始下标 + * @param {*} high 结束下标 + */ +function partition(arr, low, high) { + const pivot = arr[high]; // 默认以最后一个数为枢纽 + while (low < high) { + // low找比pivot大的数 + while (low < high && arr[low] < pivot) { + low++; + } + arr[high] = arr[low]; + while (low < high && arr[high] > pivot) { + high--; + } + arr[low] = arr[high]; + } + arr[low] = pivot; + return low; +} + +// test + +const arr = [11, 9, 6, 17, 0, 1, 2, 18, 3, 4, 8, 5]; +const ret = topK(arr, 100); +console.log(ret);