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/
可以用棧儲存狀態 也就是高階語言實作遞歸的本質
雷雷