-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmsort.h
83 lines (69 loc) · 1.63 KB
/
msort.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#ifndef MSORT_
#define MSORT_
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <math.h>
#include <set>
#include "review.h"
#include "product.h"
struct AlphaStrComp {
bool operator()(const Product* lhs, const Product* rhs)
{ // Uses string's built in operator<
// to do lexicographic (alphabetical) comparison
return lhs->getName() < rhs->getName();
}
};
struct ReviewComp{
bool operator()(const Review* lhs, const Review* rhs){
return *lhs < *rhs;//lhs->operator<(*rhs);
}
};
struct RateComt{
bool operator()(const Product* lhs, const Product* rhs){
return lhs->getAverage() < rhs->getAverage();
}
};
template <class T, class Comparator>
void merge(std::vector<T>& v, double low, double middle, double high, Comparator comp){
std::vector<T> temp;
for(int i = low; i<=high; ++i)
temp.push_back(v[i]);
int i = low;
int j = middle +1;
int k = low;
while( i <= middle && j <= high){
if(comp(temp[i-low], temp[j-low])){
v[k] = temp[i-low];
++i;
}
else{
v[k] = temp[j-low];
++j;
}
++k;
}
while(i <= middle){
v[k] = temp[i-low];
++k;
++i;
}
}
template <class T, class Comparator>
void helper1_(std::vector<T>& v, int low, int high, Comparator comp){
if(low < high){
int middle = (low+high)/2;
helper1_(v, low, middle, comp);
helper1_(v, middle+1, high, comp);
merge(v, low, middle, high, comp);
}
}
template <class T, class Comparator>
void mergeSort(std::vector<T>& vec_, Comparator comp){
if(vec_.size() == 0)
return;
helper1_(vec_, 0, vec_.size() -1, comp);
return;
}
#endif