From 65ae51a5c6e11bf45d43947b667e780786828986 Mon Sep 17 00:00:00 2001 From: yigencong Date: Mon, 26 Feb 2024 23:38:11 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=B7=BB=E5=8A=A0=E9=9D=9E?= =?UTF-8?q?=E9=80=92=E5=BD=92=E6=96=B9=E5=BC=8F=E7=9A=84=E5=BF=AB=E9=80=9F?= =?UTF-8?q?=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sort/quick-sort.mjs | 48 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/sort/quick-sort.mjs b/sort/quick-sort.mjs index b769333..8f9e4a9 100644 --- a/sort/quick-sort.mjs +++ b/sort/quick-sort.mjs @@ -140,11 +140,57 @@ function partition3(arr, left, right){ return pre + 1 } +/** + * @description 使用非递归方式实现快速排序 + * @param {number[]} arr - 需要排序的数组 + */ +export function quickSort4(arr){ + if ( !arr.length || arr.length ==1 ) return // 数组为空,或者数组为1,不处理 + let left = 0 + let right = arr.length - 1 + const stack = [] // js的数组有push和pop符合栈结构 + stack.push(right) + stack.push(left) + while(stack.length) { + const l = stack.pop() // 弹出需要处理的左边l + const r = stack.pop() // 弹出需要处理的有边界 + const pivot = partition4(arr, l, r) + // l < pivot - 1 说明还可以分,当l = pivot -1 说明pivot左侧就一个数,说明左侧已经有序了无须再分 + if(l < pivot - 1) { + stack.push(pivot - 1) + stack.push(l) + } + if(right > pivot + 1) { + stack.push(r) + stack.push(pivot + 1) + } + + } +} + +export function quickSort5(arr) { + let stack = [] + stack.push(arr.length - 1) + stack.push(0) + while(stack.length) { + let l = stack.pop() + let r = stack.pop() + let index = partition4(arr, l, r) + if (l < index - 1) { + stack.push(index-1) + stack.push(l) + } + if(r > index+1){ + stack.push(r) + stack.push(index + 1) + } + } +} + /* 1000000个数据测试下来发现,partition ,partition3和4基本上无区别,而且4只是减少了代码,并没有减少执行 过程,而且使代码变得难以理解,不推荐使用,推荐使用挖坑法来分数组, Function execution time: 464.513192 milliseconds Function execution time: 418.692408 milliseconds Function execution time: 467.99971000000005 milliseconds - */