#include <iostream>
#include <c++/vector>
#include <c++/algorithm>
using namespace std;
// 两种快速排序
int qsort_rec(vector<int>* elems_i,int left, int right){
auto iter_elems = elems_i->begin();
if(left>=right){return 0;}
int i = left;
int j = right;
int k = *(iter_elems+i);
while(i<j){
while(i<j&&*(iter_elems+j)>=k){
j --;
}
if(i<j){
*(iter_elems+i) = *(iter_elems+j);
i++;
}
while(i<j&&*(iter_elems+i)<k){
i++;
}
if(i<j){
*(iter_elems+j) = *(iter_elems+i);
j--;
}
}
*(iter_elems+i) = k;
qsort_rec(elems_i, left, i -1);
qsort_rec(elems_i, i + 1, right);
}
void fast_sort(vector<int>* i){
auto end = static_cast<int>(i->size());
qsort_rec(i, 0, end-1);
}
int qsort_rec_simple(vector<int>* elems, int left, int right){
auto iter_elems = elems->begin();
if(left>=right){
return 0;
}
int k = *(iter_elems+ left);
int i = left;
for(int j = left+1;j <= right;j++){
if(*(iter_elems+j)<k){
i++;
int temp = *(iter_elems+i);
*(iter_elems+i) = *(iter_elems+j);
*(iter_elems+j) = temp;
}
}
swap(*(iter_elems+left), *(iter_elems+i));
qsort_rec_simple(elems, left, i-1);
qsort_rec_simple(elems, i+1, right);
}
void quick_sort_simple(vector<int>* i){
auto end = static_cast<int>(i->size());
qsort_rec_simple(i, 0, end - 1);
};
void built_in_sort(vector<int>* i){
sort(i->begin(), i->end());
stable_sort(i->begin(), i->end());
}
//归并排序 merge sort
void merge(vector<int>* lfrom, vector<int>* lto, int low, int mid, int high){
int i = low;
int j = mid;
int k = low;
while(i<mid&&j<high){
if(*(lfrom->begin()+i) < *(lfrom->begin()+j)){
*(lto->begin()+k) = *(lfrom->begin()+i);
i++;
}
else{
*(lto->begin()+k) = *(lfrom->begin()+j);
j++;
}
k++;
}
while(i<mid){
*(lto->begin()+k) = *(lfrom->begin()+i);
i++;
k++;
}
while(j < high){
*(lto->begin()+k) = *(lfrom->begin()+j);
j++;
k++;
}
}
void merge_pass(vector<int>* lfrom, vector<int>* lto, int llen, int slen){
int i = 0;
while(i+2*slen < llen){
merge(lfrom, lto, i, i+slen, i+2*slen);
i += 2 *slen;
}
if(i+slen<llen){
merge(lfrom, lto, i, i+slen, llen);
}
else{
for(int j = i;j<llen;j++){
*(lto->begin()+j) = *(lfrom->begin()+j);
}
}
}
void merge_sort(vector<int>* i){
int slice_len = 1;
auto list_len = static_cast<int>(i->size());
vector<int> temp_list(i->size());
vector<int>* ptr_t = &temp_list;
while(slice_len < list_len){
merge_pass(i, ptr_t, list_len, slice_len);
slice_len *= 2;
merge_pass(ptr_t, i, list_len, slice_len);
slice_len *= 2;
}
}
转载于:https://www.cnblogs.com/theodoric008/p/7967963.html