Created
October 5, 2020 06:04
-
-
Save misterpoloy/1c9b2c64dbc67ec3e95c7b7d34c15c9e to your computer and use it in GitHub Desktop.
Merge sort implementation c++
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 <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