-
Notifications
You must be signed in to change notification settings - Fork 3
/
mergeSort.cpp
49 lines (40 loc) · 1.23 KB
/
mergeSort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <vector>
// Merges the vector into a new vector
// Time: O(n), Space: O(n)
void merge(std::vector<int> &vec, int left, int mid, int right) {
int size = right - left + 1;
// New merged vector
std::vector<int> merged(size);
for (int i = left, j = mid + 1, k = 0; k < size; ++k) {
if (i > mid)
merged[k] = vec[j++];
else if (j > right)
merged[k] = vec[i++];
else
merged[k] = (vec[i] <= vec[j]) ? vec[i++] : vec[j++];
}
std::copy(merged.begin(), merged.end(), vec.begin() + left);
}
void merge_sort(std::vector<int> &vec, int left, int right) {
if (right <= left) return;
// Recurse
int mid = (right + left) / 2; // Possible case of overflow here
merge_sort(vec, left, mid);
merge_sort(vec, mid + 1, right);
merge(vec, left, mid, right);
}
int main() {
std::vector<int> vec = { 5, 3, 10, 7, 30, 30, 23, 21 };
std::cout << "Before:" << std::endl;
for (int n : vec) {
std::cout << n << " ";
}
std::cout << std::endl;
merge_sort(vec, 0, vec.size() - 1);
std::cout << "After:" << std::endl;
for (int n : vec) {
std::cout << n << " ";
}
std::cout << std::endl;
}