正宗快速排序算法

正宗快速排序算法C++版本,看图一目了然。

归并排序和快速排序都用到了分治思想。这两种排序算法适合大规模的数据排序。

平均时间复杂度O(nlogn)。
空间复杂度O(logn)~O(n)。

#include <iostream>
#include <vector>
#include <stack>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
#include "TreeNode.h"
using namespace std;

void mySwap(int num[], int i, int j){
    int temp = num[i];
    num[i] = num[j];
    num[j] = temp;
}

int Partition(int num[], int start, int end){
    int pivotKey;
    // 将第一个记录作为分区点
    pivotKey = num[start];
    while(start < end){
        while(start < end && num[end] >= pivotKey)
            end--;
        mySwap(num, start, end);
        while(start < end && num[start] <= pivotKey)
            start++;
        mySwap(num, start, end);
    }
    return start;
}

// 对num数组的start到end区间进行快速排序
void QuickSort(int num[], int start, int end){
    if(start >= end)
        return ;
    // 定义分区点
    int pivot = Partition(num, start, end);
    QuickSort(num, start, pivot - 1);
    QuickSort(num, pivot + 1, end);
}


int main(int argc, char* argv[]){
    int arr[8] = {8,7,6,5,4,3,2,1};
    QuickSort(arr, 0, 7);
    for(int i = 0; i < 8; i++){
        cout<<arr[i]<<"\t";
    }
    return 0;
}
posted @ 2020-08-01 10:31  程序员曾奈斯  阅读(145)  评论(0)    收藏  举报