public class QuickSort {
public static void main(String[] args) {
int[] a = {8, 15, 2, 3, 4, 67, 12, 7, 13, 5, 9};
System.out.println(Arrays.toString(a));
sort(a);
System.out.println(Arrays.toString(a));
}
public static void sort(int[] arr) {
if (arr.length > 0) {
quickSort(arr, 0, arr.length - 1);
}
}
private static void quickSort(int[] arr, int low, int high) {
if (low > high) {
return;
}
int i = low;
int j = high;
int base = arr[low];
while (i < j) {
while (i < j && arr[j] > base) {
j--;
}
while (i < j && arr[i] <= base) {
i++;
}
if (i < j) {
int tem = arr[i];
arr[i] = arr[j];
arr[j] = tem;
}
}
int temp = arr[i];
arr[i] = arr[low];
arr[low] = temp;
quickSort(arr, low, i - 1);
quickSort(arr, i + 1, high);
}
}
结果输出:
时间复杂度:
最差时间复杂度:O(n²)
平均时间复杂度:O(nlogn)