public class QuickSortTwo {
private QuickSortTwo() {
}
public static <E extends Comparable<E>> void sort(E[] arr) {
Random random = new Random();
sort(arr, 0, arr.length - 1, random);
}
private static <E extends Comparable<E>> void sort(E[] arr, int l, int r, Random random) {
if (l >= r) {
return;
}
int p = partition(arr, l, r, random);
sort(arr, l, p - 1, random);
sort(arr, p + 1, r, random);
}
private static <E extends Comparable<E>> int partition(E[] arr, int l, int r, Random random) {
int p = l + random.nextInt(r - l + 1);
swap(arr, l, p);
int i = l + 1,j = r;
while(true){
while(i <= j && arr[i].compareTo(arr[l]) < 0){
i++;
}
while(j >= i && arr[j].compareTo(arr[l]) > 0){
j--;
}
if(i >= j){
break;
}
swap(arr,i,j);
i++;
j--;
}
swap(arr,l,j);
return j;
}
private static <E extends Comparable<E>> void swap(E[] arr, int i, int j) {
E temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int n = 100000;
Integer[] arr = ArrayGeneratorUtil.generateRandomArray(n,n);
Integer[] arr2 = Arrays.copyOf(arr,arr.length);
System.out.println("Random Array");
SortHelper.sortTest(arr,"QuickSort");
SortHelper.sortTest(arr2,"QuickSortTwo");
System.out.println();
arr = ArrayGeneratorUtil.generateOrderedArray(n);
arr2 = Arrays.copyOf(arr,arr.length);
System.out.println("Order Array");
SortHelper.sortTest(arr,"QuickSort");
SortHelper.sortTest(arr2,"QuickSortTwo");
System.out.println();
arr = ArrayGeneratorUtil.generateRandomArray(n,1);
arr2 = Arrays.copyOf(arr,arr.length);
System.out.println("Same Array");
SortHelper.sortTest(arr,"QuickSort");
SortHelper.sortTest(arr2,"QuickSortTwo");
System.out.println();
}
}
备注:通用版快速排序,适合所有场景
① 随机生成的数组 ② 有序数组 ③ 数组元素都相同的数组