public class ArrayUtils{
public static void main(String[] args) {
int[] arr={1,3,2,5,6,4};
sort(arr);
System.out.println(Arrays.toString(arr));
}
private static final int MAX_RUN_COUNT = 67;
private static final int MAX_RUN_LENGTH = 33;
private static final int QUICKSORT_THRESHOLD = 286;
private static final int INSERTION_SORT_THRESHOLD = 47;
//高手请把这个排序的思路讲明白!!包括这些常量为什么这么定义??
public static void sort(int[] a) {
sort(a, 0, a.length - 1);
}
public static void sort(int[] a, int left, int right) {
if (right - left < QUICKSORT_THRESHOLD) {
sort(a, left, right, true);
return;
}
int[] run = new int[MAX_RUN_COUNT + 1];
int count = 0; run[0] = left;
for (int k = left; k < right; run[count] = k) {
if (a[k] < a[k + 1]) { // ascending
while (++k <= right && a[k - 1] <= a[k]);
} else if (a[k] > a[k + 1]) { // descending
while (++k <= right && a[k - 1] >= a[k]);
for (int lo = run[count] - 1, hi = k; ++lo < --hi; ) {
int t = a[lo]; a[lo] = a[hi]; a[hi] = t;
}
} else { // equal
for (int m = MAX_RUN_LENGTH; ++k <= right && a[k - 1] == a[k]; ) {
if (--m == 0) {
sort(a, left, right, true);
return;
}
}
}
if (++count == MAX_RUN_COUNT) {
sort(a, left, right, true);
return;
}
}
if (run[count] == right++) {
run[++count] = right;
} else if (count == 1) {
return;
}
int[] b; byte odd = 0;
for (int n = 1; (n <<= 1) < count; odd ^= 1);
if (odd == 0) {
b = a; a = new int[b.length];
for (int i = left - 1; ++i < right; a = b);
} else {
b = new int[a.length];
}
for (int last; count > 1; count = last) {
for (int k = (last = 0) + 2; k <= count; k += 2) {
int hi = run[k], mi = run[k - 1];
for (int i = run[k - 2], p = i, q = mi; i < hi; ++i) {
if (q >= hi || p < mi && a[p] <= a[q]) {
b = a[p++];
} else {
b = a[q++];
}
}
run[++last] = hi;
}
if ((count & 1) != 0) {
for (int i = right, lo = run[count - 1]; --i >= lo;
b = a
);
run[++last] = right;
}
int[] t = a; a = b; b = t;
}
}
private static void sort(int[] a, int left, int right, boolean leftmost) {
int length = right - left + 1;
if (length < INSERTION_SORT_THRESHOLD) {
if (leftmost) {
for (int i = left, j = i; i < right; j = ++i) {
int ai = a[i + 1];
while (ai < a[j]) {
a[j + 1] = a[j];
if (j-- == left) {
break;
}
}
a[j + 1] = ai;
}
} else {
do {
if (left >= right) {
return;
}
} while (a[++left] >= a[left - 1]);
for (int k = left; ++left <= right; k = ++left) {
int a1 = a[k], a2 = a[left];