public class Quick {
public static void sort(Comparable[] 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);
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 + 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;
echo(a,i,j);
}
echo(a,lo,j);
return j;
}
public static boolean less(Comparable v,Comparable w){
return v.compareTo(w) < 0;
}
public static void echo(Comparable[] a,int i,int j){
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
public static void show(Comparable[] a){
for(int i = 0; i < a.length;i++ ){
System.out.print(a[i] + " ");
}
}
public static boolean isSorted(Comparable[] a){
for(int i = 1; i < a.length;i++){
if(less(a[i],a[i-1])) return false;
}
return true;
}
public static Comparable[] Random(int num){
Integer[] a = new Integer[num];
Random rand = new Random();
for(int i = 0;i<num;i++){
a[i] = rand.nextInt(100000);
}
return a;
}
public static void main(String[] args) {
Comparable[] a = Selection.Random(20000000);
/*show(a);*/
Long start = System.currentTimeMillis();
sort(a);
Long end = System.currentTimeMillis();
System.out.println("Time is " + (end - start));
/*show(a);*/
}
}
特点:每一次切分,就会找到一个正确值a[j]。
难点:在切分partition(),一般随意找a[lo]作为切分元素,比它小的在左边,比它大的在右边。 通过从左开始扫描,找到比它大的,从右扫描,找到比它小的,然后两者进行交换,直到i >= j才结束;在把a[lo]和a[j]交换。