1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| private void sort(Comparable[] a, int lo, int hi) { if(lo < hi) return; //切分 int j = partition(a, lo, hi); sort(a, lo, j-1); sort(a, j+1, hi); }
//快排的切分,主要排序逻辑 private void partition(Comparable[] a, int lo, int hi) { int i = lo, j = hi+1; //切分元素 Comparable v = a[lo]; //检查是否扫描结束并交换元素 while(true) { while(less(a[++i], v)) if(i == hi) break; while(less(v, a[--j]) if(j == lo) break; if(i >= j) break; exchange(a, i, j); } // 跳出以上循环,i>=j, 并且a[j]<=a[lo] exchange(a, lo, j); //完成了 a[lo..j-1] <= a[j] <= a[j+1.. hi] return j; }
private int less(Comparable a, Comparable b) { return c.compareTo(b) < 0; }
private exchange(Comparable[] a, int i, int j) { Comparable t = a[i]; a[i] = a[j]; a[j] = t; }
|