com.sunny.sort
public class QuickSort{
public static void main(String[] args){
Integer[] a = {1,2,6,1,10,7,80,16,17,19,18,26,21};
sort(a);
show(a);
}
/**
* 快速排序算法
*/
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);
}
/**
* 快速排序的切分
*/
private 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;
}
exch(a, i, j);
}
exch(a, lo, j);
return j;
}
/**
*判断v是否小于w
*/
private static boolean less(Comparable v, Comparable w){
return v.compareTo(w)<0;
}
/**
* 交换元素 a[i] 和a[j] 的位置
*/
private static void exch(Comparable[] a, int i, int j){
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
/**
* 打印数组a中的元素
*/
public static void show(Comparable[] a){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+”,”);
}
}
}