正宗快速排序算法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;
}

相关文章:

  • 2022-02-23
  • 2021-07-19
  • 2021-08-28
  • 2021-10-11
  • 2021-12-28
  • 2021-10-23
  • 2021-06-27
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-28
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案