-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSort.cpp
More file actions
50 lines (44 loc) · 1.07 KB
/
mergeSort.cpp
File metadata and controls
50 lines (44 loc) · 1.07 KB
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 <bits/stdc++.h>
using namespace std;
void merge (vector<int> &a, int start, int mid, int end) {
vector<int> b(a.size());
int i = start, j = mid+1, count = start;
while (i <= mid || j <= end) {
if (i <= mid && j <= end) {
if (a[i] <= a[j]) {
b[count] = a[i];
i++;
}
else {
b[count] = a[j];
j++;
}
}
else if (i <= mid) {
b[count] = a[i];
i++;
}
else {
b[count] = a[j];
j++;
}
count++;
}
for (int i = start; i <= end; i++) {
a[i] = b[i];
}
}
void mergeSort(vector<int> &a, int start, int end) {
if (start < end) {
int mid = start + (end-start) / 2;
mergeSort(a, start, mid);
mergeSort(a, mid+1, end);
merge(a, start, mid, end);
}
}
int main() {
vector<int> a = {9, 10, 3, 2, 8, 7, 100, 25, 3, 1};
mergeSort(a, 0, a.size()-1);
for (auto& x : a) cout << x << " ";
cout << endl;
}