经典快速排序:
public class Solution3 {
// 快速排序 1:基本快速排序
public static void main(String[] args) {
// int[] a = {-74, 48, -20, 2, 10, -84, -5, -9, 11, -24, -91, 2, -71, 64, 63, 80, 28, -30, -58, -11, -44, -87, -22, 54, -74, -10, -55, -28, -46, 29, 10, 50, -72, 34, 26, 25, 8, 51, 13, 30, 35, -8, 50, 65, -6, 16, -2, 21, -78, 35, -13, 14, 23, -3, 26, -90, 86, 25, -56, 91, -13, 92, -25, 37, 57, -20, -69, 98, 95, 45, 47, 29, 86, -28, 73, -44, -46, 65, -84, -96, -24, -12, 72, -68, 93, 57, 92, 52, -45, -2, 85, -63, 56, 55, 12, -85, 77, -39};
int[] a = {12, 13, 7, 14, 8};
Solution3 solution = new Solution3();
solution.quickSort(a, 0, a.length - 1);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + ",");
}
}
private int[] quickSort(int[] arr, int left, int right) {
if (left < right) {
int partitionIndex = getMiddle(arr, left, right);
quickSort(arr, left, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, right);
}
return arr;
}
//12, 13, 7, 14, 8
private int getMiddle(int[] a, int left, int right) {
int temp = a[left];
int index = left + 1;
for (int i = index; i <= right; i++) {
if (a[i] < temp){
swap(a,index, i);
index++;
}
}
swap(a, index-1, left);
return index - 1;
}
private void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}