源码系列:快速排序

quick_sort.cpp

#include <iostream>
#include <vector>
#include <iterator>
#include <ctime>
#include <algorithm>

using namespace std;

namespace algo
{
    /// 随机采样快排 平均效率O(nlgn)且常数因子很小 最坏效率O(n^2)
    void QuickSort(vector<int> &toSort,int beginIndex,int endIndex)
    {
        if(beginIndex < endIndex)
        {
            int random_swap = (rand() % (endIndex - beginIndex + 1)) + beginIndex;
            swap(toSort[random_swap],toSort[endIndex]);

            int i = beginIndex;

            for(int j=beginIndex;j!=endIndex;j++)
            {
                if(toSort[j] < toSort[endIndex])
                {
                    swap(toSort[i],toSort[j]);
                    i++;
                }
            }
            swap(toSort[i],toSort[endIndex]);

            QuickSort(toSort,beginIndex,i-1);
            QuickSort(toSort,i+1,endIndex);
        }
    }
}
测试代码:

#include <iostream>
#include <vector>
#include <ctime>
#include <iterator>
#include "quick_sort.cpp"

using namespace std;

int main()
{
    cout << "快速排序" << endl;
    vector<int> toSort;
    for(int i=0;i<100;i++)
    {
        toSort.push_back(rand());
    }
    cout << "随机填充100个数:" << endl;
    copy(toSort.begin(),toSort.end(),ostream_iterator<int>(cout,"\t"));
    algo::QuickSort(toSort,0,toSort.size()-1);
    cout << endl << "快排结果:" << endl;
    copy(toSort.begin(),toSort.end(),ostream_iterator<int>(cout,"\t"));
    return 0;
}

测试结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值