小练手,自写快排,注意函数的引用传递(若采用数组则不必,因vector是一个模板,当采用值传递时将会调用拷贝构造函数生成一个临时类,达不到修改原vector的目的)
若判断key时不带等号,当出现两个同样的值时会导致无限递归(导致stack overflow)
不稳定(示例:6 6 5),最佳时间复杂度nlogn,最差n^2
#include<iostream>
#include<string>
#include<vector>
using namespace std;
void test(vector<int>& vec, int left, int right) {
if (left >= right) return;
int beg = left, end = right;
int key = vec[left];
while (left < right){
while (left < right && vec[right] >= key)
right--;
vec[left] = vec[right];
while (right > left && vec[left] <= key)
left++;
vec[right] = vec[left];
}
vec[left] = key;
test(vec, beg, left - 1);
test(vec, left + 1, end);
}
int main(){
vector<int> vec = { 3,1,2,4,6,9,8,7,5,0,5 };
cout << "排序前:";
for (auto i : vec)
cout << i << " ";
cout << endl;
test(vec, 0, vec.size() - 1);
cout << "排序后:";
for (auto i : vec)
cout << i << " ";
cout << endl;
system("pause");
return 0;
}