Created
May 30, 2018 12:37
-
-
Save Goblin80/f541481aa95831134438adaddedbcd71 to your computer and use it in GitHub Desktop.
General purpose merge sort implementation in C++11
This file contains hidden or 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> | |
using namespace std; | |
template <typename T> | |
void _Merge(vector<T> &a, int low, int mid, int high) | |
{ | |
int n, p, q, | |
l = mid - low + 1, | |
r = high - mid; | |
auto v = a.begin(); | |
vector<T> left (v + low, v + mid + 1), | |
right (v + mid + 1, v + high + 1); | |
for(n = low, p = q = 0; p < l && q < r; n++) | |
a[n] = left[p] < right[q] ? left[p++] : right[q++]; | |
while(p < l) | |
a[n++] = left[p++]; | |
while(q < r) | |
a[n++] = right[q++]; | |
} | |
template <typename T> | |
void _Sort(vector<T> &a, int low, int high) | |
{ | |
if(low + 1 > high) return; | |
int mid = (low + high) / 2; | |
_Sort(a, low, mid); | |
_Sort(a, mid + 1, high); | |
_Merge(a, low, mid, high); | |
} | |
int main() | |
{ | |
vector<int> a = {38, 27, 43, 3, 9, 82, 10}; | |
int n = a.size(); | |
_Sort(a, 0, n - 1); | |
for(int i = 0; i < n; i++) | |
cout << a[i] << ",\n"[i == n - 1]; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment