快速排序(C++实现)

基本思想

任取一个元素为中心,所有比它的元素一律前放,比他的元素一律后放,形成左右两个子表;对各子表重新选择中心元素并依此规则调整,直到每个子表的元素只剩一个

通过一趟排序,将待排序记录分割成独立的两部分,其中一部分记录的关键字都比两一部分记录的关键字小,则可对这两部分记录进行排序,以达到整个序列有序。

调试代码

#include <iostream>
#include <vector>
using namespace std;
int counter = 0;//调试用

int Partition(vector<int>&vec, int low, int high)
{
    //首先以第一个元素的值作为枢轴的值,此时它所在的位置空出来,然后从后往前遍历,将第一个小于枢轴的值的元素放到空位
    int pivotVal = vec[low];   // 选取第一个元素的值作为枢轴的值
    while (low < high)
    {
        while (low < high && vec[high] >= pivotVal) high--;   // 从后往前遍历,直到遇到比枢轴小的元素时停下
        swap(vec[low], vec[high]);
        while (low < high && vec[low] <= pivotVal) low++;    // 从前往后遍历,直到遇到比枢轴大的元素时停下
        swap(vec[low], vec[high]);
    }
    vec[low] = pivotVal;

    cout << "第" << ++counter << "趟: ";
    for (int i = 0; i < 11; i++)
        cout << vec[i] << "   ";
    cout << endl << endl;
    return low;
}
void quick_sort(vector<int>& vec, int low, int high)
{
    if (low < high)
    {
        int pivot = Partition(vec, low, high);  // 确定枢轴的位置
        quick_sort(vec, low, pivot - 1);        // 对 左边子序列 递归排序
        quick_sort(vec, pivot + 1, high);       // 对 右边子序列 递归排序
    }
}
int main(int argc, const char* argv[])
{
    vector<int> vec = { 100, 1, 53, 5, 36, 7, 8, 109,  10, 11, 15 };
    cout << "待排序数组: ";
    for (int i = 0; i < 11; i++)
        cout << vec[i] << " ";
    cout << endl << endl;
    quick_sort(vec, 0, vec.size() - 1);

    cout << "结果: ";
    for (int i = 0; i < 11; i++)
        cout << vec[i] << " ";
    cout << endl << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值