- public class Quick {
- public static void sort(Comparable[] a) {
- StdRandom.shuffle(a);
- sort(a,0,a.length-1);
- }
- public static void sort(Comparable[] a, int lo, int hi) {
- if(hi<=lo) return;
- int j=partition(a,lo,hi); //j前的元素不大于a[j],j后的元素不小于a[j]
- sort(a,lo,j-1);
- sort(a,j+1,hi);
- }
- public static int partition(Comparable[] a, int lo, int hi) {
- int i=lo;
- int j=hi;
- 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;
- exch(a,i,j);
- }
- exch(a,lo,j);
- return j;
- }
- public static void exch(Comparable[] a, int i, int min) {
- Comparable t=a[i];
- a[i]=a[min];
- a[min]=t;
- }
- public static boolean less(Comparable v, Comparable w) {
- return v.compareTo(w)<0;
- }
- }
复制代码 |