public void quickSort3Way(Comparable[] arr, int n) {
quickSort3Way(arr, 0, n-1);
}
/**
* 三路快排
* @param arr 数组
* @param l 左边界
* @param r 右边界
*/
private void quickSort3Way(Comparable[] arr, int l, int r) {
swap(arr, l, (int) (Math.random()*(r-l+1)) + l);
Comparable v = arr[l];
int lt = l; //arr[l+1...lt] < v
int gt = r + 1; //arr[gt...r] = v
int i = l+1; //arr[lt + 1 ... i)=v
while (i < gt) {
if (arr[i].compareTo(v) < 0) {
swap(arr, i, lt+1);
lt++;
i++;
} else if (arr[i].compareTo(v) > 0) {
swap(arr, i, gt - 1);
gt--;
} else {
i++;
}
}
swap(arr, l, lt);
quickSort3Way(arr, l, lt-1);
quickSort3Way(arr, gt, r);
}
private static void swap(Object[] arr, int i, int j) {
Object t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}