refactor: 添加非递归方式的快速排序
This commit is contained in:
parent
6f63f7e335
commit
65ae51a5c6
@ -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
|
||||
|
||||
*/
|
||||
|
Loading…
x
Reference in New Issue
Block a user