排序算法之快速排序

本文提供了C++实现的快速排序算法源代码,并介绍了递归与非递归两种实现方式。详细解析了partition函数的作用及其实现细节,同时讨论了快速排序的时间与空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++源代码:

#include<iostream>
using namespace std;
int partition(int * a, int low, int high){ 
//指定数组a中的一个元素pos,使pos这个元素
//在正确的位置上,即pos左边的元素都小于等于pos,右边的元素都大于等于pos
    int pos = a[low];
    while (low<high){
        while (low < high&&a[high] > pos)
            high--;
        a[low] = a[high];
        while (low < high&&a[low] < pos)
            low++;
        a[high] = a[low];
    }
    a[low] = pos;
    return low;

}
void QuickSort(int * a, int low, int high){
    if (low < high){
        int p = pasition(a, low, high);
        QuickSort(a, low, p - 1);
        QuickSort(a, p + 1, high);
    }
}
int main(){
    int a[] = { 8, 5, 2, 3, 6, 7, 4, 9 };

    QuickSort(a, 0, 7);
    for (int i = 0; i <= 7; i++)
        cout << a[i] <<  endl;
}

非递归:

#include<iostream>
#include<Queue>
class LH
{
public:
    LH(int l, int h){
        low = l;
        high = h;
    }
    int low;
    int high;
};
using namespace std;
int Partition(int * a, int low, int high){
    int pos = a[low];
    while (low<high){
        while (low < high&&a[high] > pos)
            high--;
        a[low] = a[high];
        while (low < high&&a[low] < pos)
            low++;
        a[high] = a[low];

    }
    a[low] = pos;
    return low;

}
void QuickSort(int * a, int low, int high){
    queue<LH> que;
    que.push(LH(low, high));
    while (!que.empty()){
        LH lh = que.front();
        que.pop();
        int pos = Partition(a, lh.low, lh.high);
        if (lh.low < pos - 1)
            que.push(LH(lh.low, pos - 1));
        if (lh.high > pos + 1)
            que.push(LH(pos + 1, lh.high));
    }
}
int main(){
    int a[] = { 8, 5, 2, 3, 6, 7, 4, 9 };

    QuickSort(a, 0, 7);
    for (int i = 0; i <= 7; i++)
        cout << a[i] <<  endl;

}

以上是可以运行的代码,当然,position函数还有另一种写法,两者作用是完全一样的

int pasition(int * a, int low, int high){
    int pos = a[low];
    while (low<high){
        while (low < high&&a[high] > pos)
            high--;
        //a[low] = a[high];
        int c = a[low]; a[low] = a[high]; a[high] = c;
        while (low < high&&a[low] < pos)
            low++;
        //a[high] = a[low];
        c = a[low]; a[low] = a[high]; a[high] = c;
    }
    //a[low] = pos;
    return low;
}
。。。最好情况最坏情况
时间复杂度O(nlog2n)O(n2)
空间复杂度O(log2n)O(n)
情况每次划分都能从中间划分元素有序或者逆序

快速排序时间复杂度推导
http://blog.youkuaiyun.com/weshjiness/article/details/8660583

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值