C++排序(5)——快速排序

#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;

//快速排序
//时间复杂度O(N*logN)
//额外空间复杂度O(logN)

int Random_mum(int len)
{
    srand((unsigned)time(NULL));
    return rand() % len;
}

void swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

int *Quick_Sorts(vector <int> &num_s, int left, int right)
{
    int mun0 = num_s[right];
    int p = left - 1;
    int q = right;
    int curr = left;
    while(curr < q)
    {
        if(num_s[curr] < mun0)
            swap(num_s[++p], num_s[curr++]);
        else if(num_s[curr] > mun0)
            swap(num_s[--q], num_s[curr]);
        else
            curr++;
    }
    swap(num_s[curr], num_s[right]);
    int *temp_s = new int [2];
    temp_s[0] = ++p;
    temp_s[1] = q;
    return temp_s;
}

void Quick_Sort(vector <int> &num_s, int left, int right)
{
    if (left >= right)
        return ;
    swap(num_s[left + Random_mum(right - left + 1)], num_s[right]);//left 下标不要忘
    int *temp_s = new int [2];
    temp_s = Quick_Sorts(num_s, left, right);
    Quick_Sort(num_s, left, temp_s[0] - 1);
    Quick_Sort(num_s, temp_s[0] + 1, right);
}

void QuickSort(vector <int> &num_s)
{
    if(num_s.size() <= 1)
        return ; 
    int left = 0;
    int right = num_s.size() - 1;
    Quick_Sort(num_s, left, right);
}

int main()
{
    int num0;
    vector <int> num_s;
    while (cin >> num0)
        num_s.push_back(num0);
    cout << "the original data is: " << endl;
    for (int i = 0; i < num_s.size(); i++)
        cout << num_s[i] << ' ';
    
    cout << endl << "the Quick_Sort data is: " << endl;

    QuickSort(num_s);
    
    for (int i = 0; i < num_s.size(); i++)
        cout << num_s[i] << ' ';
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值