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]); } }
import java.util.Stack; //快速排序的非递归实现,利用系统的栈stack public class QuickSortNonRecursion { public static void main(String[] args) { QuickSortNonRecursion qsnr = new QuickSortNonRecursion(); int[] array = {0, 2, 11, 121, 18, 99, 3, 5, 101, 22, 9, 100}; qsnr.quicksort(array); for (int i : array) { System.out.print(i + " "); } } public void quicksort(int[] array) { if (array == null || array.length == 1) return; //存放开始与结束索引 Stack s = new Stack(); //压栈 s.push(0); s.push(array.length - 1); //利用循环里实现 while (!s.empty()) { int right = s.pop(); int left = s.pop(); //如果最大索引小于等于左边索引,说明结束了 if (right <= left) continue; int i = partition(array, left, right); if (left < i - 1) { s.push(left); s.push(i - 1); } if (i + 1 < right) { s.push(i+1); s.push(right); } } } //找到轴心,进行交换 public int partition (int[] data, int first, int end) { int temp; int i=first,j=end; if(firsti&&data[j]>temp)j--; if(idata[i])i++; if(i
用栈储存,对着改就好了
写了两个版本,你对照一下: https://jsfiddle.net/hsfzxjy/ob8x16uz/4/
可以用栈储存状态 也就是高级语言实现递归的本质