快速排序算法 基于划分和递归实现,以下是参考《数据结构和算法分析java语言描述》第三版 中的代码实现并结合自己的测试 编写的。
public class QuickSort { private static final int CUTOFF= 0; /** * quickSort algorithm * * @param a * an array of comparable<> * @param a */ public static <AnyType extends Comparable<? super AnyType>> void quicksort(AnyType[] a) { quicksort(a, 0, a.length - 1); }
/**
* Internal quicksort method that makes recursive calls
* uses median-of-three pattitoning and a cutoff of 10
* [@param](https://my.oschina.net/u/2303379) a an array of Comparable items.
* [@param](https://my.oschina.net/u/2303379) left the left-most index of subarray
* [@param](https://my.oschina.net/u/2303379) right the right-most index of subarray
*/
private static <AnyType extends Comparable<? super AnyType>> void quicksort(AnyType[] a, int left, int right) {
if(left+CUTOFF<=right &&right>0 ){
AnyType pivot = median3(a, left, right);//找到分割点
//begin partitioning
int i=left, j=right-1;
for(;;){
while(i<right-1&&a[i].compareTo(pivot)<0 ){i++;} // a[i] >= privot
while(j>left&&a[j].compareTo(pivot)>0){j--;} // a[j] <= privot
if(i<j){
swap(a, i, j);
}else{
break;
}
}
swap(a, i, right);//restore pivot
quicksort(a,left,i-1);//sort small elements
quicksort(a,i+1,right);//sort larger elements
} else{//do an insertion sort on the subarray
// insertionSort(); }
}
/**
* return median of left ,center ,and right
* order these and hide the piovt
* @param a
* @param left
* @param right
* @return
*/
private static <AnyType extends Comparable<? super AnyType>> AnyType median3(AnyType[] a, int left, int right) {
int center = (left + right) / 2;
if (a[center].compareTo(a[left]) < 0)
swap(a, center, right);
if (a[right].compareTo(a[left]) < 0)
swap(a, right, left);
if (a[right].compareTo(a[center]) < 0)
swap(a, right, center);
// place piovt at position right-1
//使枢纽元素离开被分割的段
swap(a, center, right );
return a[right];
}
private static <AnyType extends Comparable<? super AnyType>> void swap(AnyType[] a, int left, int right) {
AnyType temp = a[left];
a[left] = a[right];
a[right] = temp;
}
}
//测试方法 public class TestApp { public static void main(String[] args) {
Integer[] a = new Integer[16];
for (int i = 0; i < 16; i++) {
a[i]=(int)(Math.random()*100);
}
display(a);
QuickSort.quicksort(a);
display(a);
}
private static void display(Integer[] a) {
for (int i = 0; i < 16; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
}
}