Last active
March 28, 2019 11:02
-
-
Save adamkorg/99cae1fa4da0bc8431d040c1e8f516fd to your computer and use it in GitHub Desktop.
Merge sort (recursive)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
template<class T> | |
void merge(std::vector<T>& vals, int l, int m, int r) { | |
//iterate through both left and right partitions, selecting | |
//the lowest value of each comparision. | |
std::vector<T> out; | |
int i=l, j=m; | |
while(out.size() <= r-l) { | |
if (j>r || vals[i]<vals[j]) | |
out.push_back(vals[i++]); | |
else if (i>=m || vals[j]<vals[i]) | |
out.push_back(vals[j++]); | |
} | |
for(int n=0; n<out.size(); n++) | |
vals[l+n] = out[n]; | |
} | |
template<class T> | |
void merge_sort(std::vector<T>& vals, int l, int r) { | |
if (r-l < 1) | |
return; | |
int m = (l+r+1) / 2; | |
merge_sort(vals, l, m-1); | |
merge_sort(vals, m, r); | |
merge(vals, l, m, r); | |
} | |
template<class T> | |
void merge_sort(std::vector<T>& vals) { | |
merge_sort(vals, 0, vals.size()-1); | |
} | |
template <class T> | |
void print_v(const std::vector<T>& vals) { | |
for (auto val : vals) | |
std::cout << val << " "; | |
std::cout << std::endl; | |
} | |
int main() | |
{ | |
std::vector<int> nums { 4,9,6,3,8,5,1,7 }; | |
print_v(nums); | |
merge_sort(nums); | |
print_v(nums); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment