function qsort_with_loop(arr) {
let stack = [];
stack.push([0, arr.length - 1]);
while (stack.length) {
let _ = stack.pop();
let i = l = _[0];
let j = r = _[1];
let mid = arr[(i + j) >> 1];
do {
while (arr[i] < mid) ++i;
while (arr[j] > mid) --j;
if (i <= j) {
let t = arr[i];
arr[i] = arr[j];
arr[j] = t;
++i;
--j;
}
} while (i <= j);
if (i < r) stack.push([i, r]);
if (l < j) stack.push([l, j]);
}
}
用栈储存,对着改就好了
写了两个版本,你对照一下: https://jsfiddle.net/hsfzxjy/ob8x16uz/4/
可以用栈储存状态 也就是高级语言实现递归的本质