Skip to content

Instantly share code, notes, and snippets.

@Goblin80
Created May 30, 2018 12:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Goblin80/f541481aa95831134438adaddedbcd71 to your computer and use it in GitHub Desktop.
Save Goblin80/f541481aa95831134438adaddedbcd71 to your computer and use it in GitHub Desktop.
General purpose merge sort implementation in C++11
#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