快速排序

快速排序算法

随机选取数组中其中一个数据作为最后一个数据来进行排序,这种方法的时间复杂度的平均值为o(nlogn)
FastSort.hpp

//
// Created by Administrator on 2021/7/28.
//

#ifndef C__TEST01_FASTSORT_HPP
#define C__TEST01_FASTSORT_HPP
#include <vector>
#include <iostream>
using namespace std;

class FastSort {
public:
    FastSort(vector<int> An);
    void process(vector<int> &A, int L, int R);
    vector<int> quickSort(vector<int> &A, int L, int R);
    void swap(vector<int> &A, int pos1, int pos2);
private:
    vector<int> A;
};
FastSort::FastSort(vector<int> An) :
A(An){
    A.resize(An.size());
}

void FastSort::process(vector<int> &A, int L, int R) {
    if(A.size() == 0||L > R){
        return;
    }
    swap(A, L + (int)rand()%(R-L+1), R);
    vector<int> p = quickSort(A, L, R);
    process(A, L, p[0]-1);
    process(A, p[1]+1, R);
}
//返回长度的左边界右边界
vector<int> FastSort::quickSort(vector<int> &A, int L, int R) {
    int less = L-1;
    int end = R;

    while(L < end){
        if(A[L] < A[R]){
            swap(A, ++less, L++);
            //less = less + 1;
            //swap(A, less, L);
            //L = L+1;
        }else if(A[L] > A[R]){
            swap(A, --end, L);
        }else{
            L++;
        }
    }
    swap(A, end, R);
    return {less+1, end};
}
void FastSort::swap(vector<int> &A, int pos1, int pos2) {
    if(pos1<0||pos2<0||pos1>A.size()-1||pos2>A.size()-1){
        return;
    }
    int temp;
    temp = A[pos1];
    A[pos1] = A[pos2];
    A[pos2] = temp;
}
#endif //C__TEST01_FASTSORT_HPP

posted @   蘑菇王国大聪明  阅读(32)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示