Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created October 5, 2020 06:04
Show Gist options
  • Save misterpoloy/1c9b2c64dbc67ec3e95c7b7d34c15c9e to your computer and use it in GitHub Desktop.
Save misterpoloy/1c9b2c64dbc67ec3e95c7b7d34c15c9e to your computer and use it in GitHub Desktop.
Merge sort implementation c++
#include <vector>
using namespace std;
vector<int> merge(vector<int> left, vector<int> right) {
vector<int> sortedArray(left.size() + right.size(), 0);
int k = 0;
int i = 0;
int j = 0;
while (i < left.size() && j < right.size()) {
if (left[i] <= right[j]) {
sortedArray[k++] = left[i++];
} else {
sortedArray[k++] = right[j++];
}
}
while (i < left.size()) sortedArray[k++] = left[i++];
while (j < right.size()) sortedArray[k++] = right[j++];
return sortedArray;
}
vector<int> mergeSort(vector<int> array) {
if (array.size() <= 1) return array;
int n = array.size();
int mid = n / 2;
vector<int> left(array.begin(), array.begin() + mid);
vector<int> right(array.begin() + mid, array.end());
return merge(mergeSort(left), mergeSort(right));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment