(完整c++)快排,快速排列,sort

tech2022-12-07  95

贴一个链接: 二十多分钟的视频,老师讲的非常清楚,倍速看十几分钟,你就会明白怎么回事。 https://www.bilibili.com/video/BV1nJ411V7bd?p=164 下面是代码实现,基于递归的思想。 注释已写进去。

#include<iostream> #include<vector> using namespace std; //sort void my_sort(vector<int> &temp, int l, int r) { if (l < r) { //pivot是队长!以他作为参考,从右边向左边开始遍历, int i = l, j = r;int pivot = temp[l]; while (i < j) { //从右向左,比队长大呢就路过,即j--; while (i < j && pivot <= temp[j]) j--; //此时找到了比队长小的A,然后令数组最左边的元素等于A if (i < j) temp[i++] = temp[j]; //从左向右,比队长小呢就路过,即i++; while (i<j && pivot>temp[i]) i++; //找到了比队长大的B,令原本A位置的值设为B的值 if (i < j) temp[j--] = temp[i]; } //队长进去 temp[i] = pivot; my_sort(temp, l, i); my_sort(temp, i + 1, r); } } int main() { std::vector<int> res; for (int i = 9;i >= 1;i--) { res.push_back(i); } int len = res.size(); my_sort(res, 0, len - 1); /* for(atuo x: res) { cout << x << " "; }*/ for (vector<int>::iterator it=res.begin();it!=res.end();it++) { cout <<* it << " " << endl; } return 0; }
最新回复(0)