快速排序

快速排序

  1. 快速排序是通过递归实现。

  2. 快速排序先选取基准值base,从两端向中间遍历,通过一次遍历将序列调整为
    [小于base的序列,base,大于base的序列] ------以从小到大为例

  3. 再通过递归,分别对小于base的序列和大于base的序列进行快速排序,最终完成排序。

Algorithm Time Complexity Space Complexity
Best Average Worst Worst
Quicksort Ω(n log(n)) Θ(n log(n) O(n^2) O(log(n))
//c++
void quickSort(vector&nums, int left, int right){
    if (left > right) return;

    int low = left;
    int high = right;
    int base = nums[left];
    
    while (low < high){
        while (nums[high] >= base and low < high){
            high--;
        }
        nums[low] = nums[high];
        
        while (nums[low] <= base and low < high){
            low++;
        }
        nums[high] = nums[low];
    }
    nums[low] = base;
    
    quickSort(nums, left, low-1);
    quickSort(nums, high+1, right);
}

你可能感兴趣的:(算法,快速排序)