标签:style blog http color os io 使用 ar for
#include<iostream>
#include<iomanip>
#include<vector>
#include<cstdlib>
#include<ctime>
#include<algorithm>
using namespace std;
inline void swap(vector<int>& num, int p, int q){
int t = num[p];
num[p] = num[q];
num[q] = t;
}
void insert_sort(vector<int>& num){
int tmp, j;
for (int i = 1; i < num.size(); i++){
tmp = num[i];
for (j = i - 1; j >= 0 && num[j] > tmp; j--)
num[j + 1] = num[j];
num[j + 1] =tmp;
}
}
int quick_sort_sub(vector<int>& num, int p, int q){
if (p >= q)
return 0;
// if 4 elements or less, use insert sort
if (p + 10 > q){
vector<int> tnum(num.begin() + p, num.begin() + q + 1);
insert_sort(tnum);
for (int i = 0; i < tnum.size(); i++)
num[p + i] = tnum[i];
}
int idx = quick_three_partition(num, p, q);
swap(num, idx, q);
int pivot = num[q];
int left = p, right = q - 1;
while (1){
while (num[left] < pivot)
++left;
while (num[right] >= pivot)
--right;
if (left < right)
swap(num, left, right);
else
break;
}
swap(num, left, q);
quick_sort_sub(num, p, left - 1);
quick_sort_sub(num, left + 1, q);
return left;
}
void quick_sort(vector<int>& num){
quick_sort_sub(num, 0, num.size() - 1);
}
int main(){
const int n = 10;
/*int num_array[n]= {2,1};
vector<int> num(num_array, num_array + n);*/
srand( time(NULL) );
vector<int> num(n);
for (auto& e : num)
e = rand() % n;
quick_sort(num);
for (auto& e : num)
cout << setw(4) << e << ‘ ‘;
cout << endl;
cout << "vector is sorted? : " << is_sorted(num.begin(), num.end()) << endl;
return 0;
}
标签:style blog http color os io 使用 ar for
原文地址:http://www.cnblogs.com/mengfanrong/p/3952128.html