package sort;
public class QuickSort {
public static final int cutoff = 3;
/**
* insertion sort
*
* @param A
* @param left
* @param right
*/
public static void insert_sort(int[] A, int left, int right) {
for (int p = left; p <= right; p++) {
int tmp = A[p];
int j;
for (j = p; j > 0 && A[j - 1] > tmp; j--) {
A[j] = A[j - 1];
}
A[j] = tmp;
}
}
public static void swap(int[] A, int i, int j) {
int x = A[i];
A[i] = A[j];
A[j] = x;
}
/**
* pick the second large number from A[left], A[center],A[right]
*
* @param A
* @param left
* @param right
* @return
*/
public static int median(int[] A, int left, int right) {
int center = (left + right) / 2;
if (A[left] > A[center])
swap(A, left, center);
if (A[left] > A[right])
swap(A, left, right);
if (A[center] > A[right])
swap(A, center, right);
swap(A, center, right - 1);
return A[right - 1];
}
public static void qsort(int[] A, int left, int right) {
if (left + cutoff <= right) {
int pivot = median(A, left, right);
int i = left;
int j = right - 1;
for (;;) {
while (A[++i] < pivot) {
}
while (--j > pivot) {
}
if (i < j) {
swap(A, i, j);
} else
break;
}
swap(A, i, right - 1);
qsort(A, left, i - 1);
qsort(A, i + 1, right);
} else {
insert_sort(A, left, right);
}
}
public static void main(String[] args) {
int[] a = { 45, 23, 12, 56, 67, 43, 37, 101, 10 };
qsort(a, 0, a.length - 1);
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}