算法分析
每次通過一趟排序將要排序的數據分割成獨立的兩部分,其中一部分的所有數據都比另外一部分的所有數據都要小,然後再按此方法對這兩部分數據分別進行快速排序,整個排序過程可以遞歸進行,以此達到整個數據變成有序序列。
時間複雜度
平均 O(nlogn) ,最差是 O(n^2)
代碼實現
java實現
private static int getMiddle(int[] arr, int low, int high){
int temp = arr[low];
while (low < high){
while (low < high && arr[high] >= temp){
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= temp){
low++;
}
arr[high] = arr[low];
}
arr[low] = temp;
//System.out.println(low + ", " + high);
return low;
}
private static void quickSort(int[] arr, int low, int high){
if(low < high){
int middle = getMiddle(arr, low, high);
quickSort(arr, 0, middle - 1);
quickSort(arr, middle + 1, high);
}
}
public static void main(String[] args){
int[] arr = {2, 5, 1, 4, 8};
quickSort(arr, 0, arr.length - 1);
for(int i = 0; i < arr.length; i++){
System.out.println(arr[i]);
}
}
參考
https://blog.csdn.net/nrsc272420199/article/details/82587933