快速排序
分治的思想
基本思想:
具体过程:
任意选取一个数据作为中心轴,为了方便,每次选取最左边的数据作为中心轴
int key=data[low];
//key=19,目标:将所有小于19的数字放在19的左边,将所有大于19的数字放在19的右边
设置左、右下标,begin下标不停得从左往右移动,扫描每个数字,若发现比key大的数字,该将该数字放在data的右边去;交替得,end下标不停得从右往左移动,扫描每个数字,若发现比key小的数字,该将该数字放在data的左边去,最终begin和end下标会在某个位置相遇,相遇的位置放key。
左右子序列排序同上。
代码:
#include <iostream>
#include <vector>
using namespace std;
void quickSort(vector<int>& nums, int low, int high) {
//退出判断
if (low >= high) return;
//选定中心轴
int key = nums[low];
int begin = low, end = high;
//交替从右往左扫描,从左往右扫描
while (begin < end) {
while (begin < end && nums[end] >= key) --end;
if (begin < end) {
nums[begin++] = nums[end];
}
while (begin < end && nums[begin] <= key) ++begin;
if (begin < end) {
nums[end--] = nums[begin];
}
}
//直到begin、end相遇
nums[begin] = key;
//左右子序列排序
quickSort(nums, low, begin - 1);
quickSort(nums, begin + 1, high);
}
int main() {
vector<int> nums = { 2,5,1,4,6 };
int n = nums.size();
quickSort(nums, 0, n - 1);
for (int i = 0; i < n; ++i) {
cout << nums[i]<<" ";
}
cout << endl;
return 0;
}
最终结果: