package com.mindle.test.sort;
import java.util.Arrays;
public class QuickSort<AnyType extends Comparable super AnyType>> {
/**
* 对于很小的数组,快速排序不如插入排序,因此需要设置截止范围,推荐在(5,20)之间
*/
private static final int CUTOFF = 10;
/**
* 快速排序
*
* @param array
* 数组
*/
public void quickSort(AnyType[] array) {
quickSort(array, 0, array.length - 1);
}
/**
* 递归用的快速排序,如果数组中的元素个数小于CUTOFF时,采用插入排序
*
* @param array
* 数组
* @param start
* 起始索引
* @param end
* 最后一个索引
*/
private void quickSort(AnyType[] array, int start, int end) {
if (start + CUTOFF <= end) {
AnyType temp = median3(array, start, end);
int i = start;
int j = end - 1;
for (;;) {
while (array[++i].compareTo(temp) < 0)
;
while (array[--j].compareTo(temp) > 0)
;
if (i < j)
swapReferences(array, i, j);
else
break;
}
swapReferences(array, i, end - 1);
quickSort(array, start, i - 1);
quickSort(array, i, end);
} else
insertionSort(array);
}
private void insertionSort(AnyType[] array) {
AnyType temp = null;
int hole;
for (int i = 1; i < array.length; i++) {
temp = array[i];
for (hole = i; hole > 0 && temp.compareTo(array[hole - 1]) < 0;)
array[hole] = array[--hole];
array[hole] = temp;
}
}
/**
* 三数中值分割法,使array[start]<=array[end-1]<=array[end],其中array[end-1]为枢纽元
*
* @param array
* 数组
* @param start
* 起始索引
* @param end
* 最后一位索引
* @return 枢纽元素
*/
private AnyType median3(AnyType[] array, int start, int end) {
int center = (start + end) / 2;
if (array[start].compareTo(array[center]) > 0)
swapReferences(array, start, center);
if (array[start].compareTo(array[end]) > 0)
swapReferences(array, start, end);
if (array[center].compareTo(array[end]) > 0)
swapReferences(array, center, end);
swapReferences(array, center, end - 1);
return array[end - 1];
}
/**
* 交换数组中的两个元素
*
* @param array
* 数组
* @param a
* 元素索引
* @param b
* 元素索引
*/
private void swapReferences(AnyType[] array, int a, int b) {
AnyType temp = array[a];
array[a] = array[b];
array[b] = temp;
}
public static void main(String[] args) {
Integer[] array = { 34, 8, 64, 51, 32, 21, 25, 58, 78, 1, 5, 12, 2, 34, 8, 64, 51, 32, 21, 25, 58, 78, 1, 5, 12,
2, 34, 8, 64, 51, 32, 21, 25, 58, 78, 1, 5, 12, 2 };
System.out.println(Arrays.toString(array));
new QuickSort().quickSort(array);
System.out.println(Arrays.toString(array));
}
}