package xwq.sort;
import xwq.util.In;
import xwq.util.StdOut;
import xwq.util.StdRandom;
/**
* 使用插入排序对快速排序进行优化
* 大数组使用快速排序递归切分,小数组使用插入排序
* @author batman
*
*/
public class QuickSortInsert {
private static int M = 10;
public static void sort(int[] a) {
partition(a, 0, a.length - 1);
}
private static void partition(int[] a, int low, int high) {
if(low>=high) return;
if((high-low+1) <= M) {
insertSort(a,low,high);
return;
}
int pos = StdRandom.uniform(low, high + 1);
int pivot = a[pos];
int l = low,h = high;
swap(a, low, pos);
while (l < h) {
while (l < h && a[h] >= pivot) h--;
if (l < h) a[l++] = a[h];
while (l < h && a[l] <= pivot) l++;
if (low < high) a[high--] = a[low];
}
a[low] = pivot;
partition(a,low,l-1);
partition(a,l+1,high);
}
private static void insertSort(int[] a,int low,int high) {
for(int i = low + 1;i <= high;i++) {
int t = a[i];
int j = i - 1;
while(j >= low && a[j] > t){
a[j+1] = a[j];
j--;
}
a[j+1] = t;
}
}
private static void swap(int a[], int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static void print(int a[]) {
for (int i = 0; i < a.length; i++)
StdOut.print(a[i] + " ");
StdOut.println();
}
public static void main(String[] args) {
int[] a = In.readInts(args[0]);
sort(a);
print(a);
}
}