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]);
}
}
Written two versions, please compare: https://jsfiddle.net/hsfzxjy/ob8x16uz/4/
Use stack to store, just change it
Written two versions, please compare: https://jsfiddle.net/hsfzxjy/ob8x16uz/4/
You can use the stack to store state, which is the essence of recursion in high-level languages