package sort;
import java.util.Arrays;
public class QuickSort {
private static final int CUTOFF = 10;
public static void main(String[] args) {
int[] a = {4,9,32,6,18,2,10,18,9,7,9,25,12};
quickSort(a);
System.out.println(Arrays.toString(a));
}
//驱动程序
public static void quickSort(int[] a){
quickSort(a, 0, a.length-1);
}
private static void quickSort(int[] a, int left, int right) {
if (left + CUTOFF <= right){
//确定枢纽元
int pivot = median3(a, left, right);
//开始分割
int i = left, j = right-1;
while(true){
//如果i和j遇到等于枢纽元的情况,则都停下并且交换
while (a[++i] < pivot){}
while (a[--j] > pivot){}
if (i < j)
swap(a, i, j);
else
break;
}
swap(a, i, right-1);
//递归地对左右两边的数组quickSort
quickSort(a, left, i-1);
quickSort(a, i+1, right);
}else{
//这时可使用插入排序等对小数组更有效的算法
insertionSort(a, left, right);
}
}
private static void insertionSort(int[] a, int left, int right) {
for (int i=left+1; i<=right; i++){
int tmp = a[i];
int j = i;
while (j > left && tmp < a[j-1]){
a[j] = a[j-1];
j--;
}
a[j] = tmp;
}
}
//执行三数中值分割法程序
private static int median3(int[] a, int left, int right){
int center = (left + right) / 2;
if (a[center] < a[left])
swap(a, left, center);
if (a[right] < a[left])
swap(a, left, right);
if (a[right] < a[center])
swap(a, center, right);
//最后把枢纽元和right-1位置的数交换
swap(a, center, right-1);
return a[right-1];
}
private static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
排序算法之快速排序
最新推荐文章于 2022-05-16 12:24:09 发布