写了一个类似STL中的sort用法的归并排序,可以以函数形式传入排序规则。
#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
template <typename T>
class MergeSort{
public:
//以仿函数实现
void operator()(vector<T>& data, function<bool(T, T)> func) {
this->func =func;
MSort(data, 0, data.size() - 1);
}
private:
//排序规则
function<bool(T, T)> func;
//归并排序
void MSort(vector<T>& data, int low, int high){
if(low >= high){
return;
}
int mid = (low+high)/2;
MSort(data, low, mid);
MSort(data, mid + 1, high);
Merge(data,low, mid, high);
}
//归并
void Merge(vector<T> &list1, const int low,const int mid, const int high){
vector<T> temp;
//预先分配100空间,提高vector效率
temp.reserve(100);
int low_iter = low;
int high_iter = mid + 1;
while (low_iter <= mid && high_iter <= high){
//以传入的判断函数进行比较
if(func(list1[low_iter] , list1[high_iter])){
temp.push_back(list1[low_iter++]);
}else{
temp.push_back(list1[high_iter++]);
}
}
if(low_iter > mid && high_iter <= high){
for(int i = high_iter; i <= high; i++)
temp.push_back(list1[i]);
}
else if(low_iter <= mid && high_iter > high){
for(int i = low_iter; i <= mid; i++){
temp.push_back(list1[i]);
}
}
for(int i = low, j = 0; i <= high; i++, j++){
list1[i] = temp[j];
}
}
};
int main(){
vector<int> a1 = {1,3,5,2,4,6,99,1,2,3};
//以lambda表达式形式传入比较函数,返回值为boolen类型
MergeSort<int>()(a1, [](int a, int b){ return a <= b;});
for_each(a1.begin(), a1.end(), [](int i){cout << i << " ";});
}