-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeSort.cpp
46 lines (40 loc) · 895 Bytes
/
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
#include <iostream>
#include <vector>
using namespace std;
void mergeArr(int *arr, int s, int e, int mid) {
int left = s;
int right = mid + 1;
vector<int> vec;
while (left <= mid && right <= e) {
if (arr[left] <= arr[right]) {
vec.push_back(arr[left++]);
} else {
vec.push_back(arr[right++]);
}
}
while (left <= mid) {
vec.push_back(arr[left++]);
}
while (right <= e) {
vec.push_back(arr[right++]);
}
for (int i = s; i <= e; i++) {
arr[i] = vec[i - s];
}
}
void mergeSort(int *arr, int s, int e) {
if (s >= e) return;
int mid = s + (e - s) / 2;
mergeSort(arr, s, mid);
mergeSort(arr, mid + 1, e);
mergeArr(arr, s, e, mid);
}
int main() {
int arr[10] = {4, 3, 7, 1, 9, 3, 6, 0, 5, -1};
mergeSort(arr, 0, sizeof(arr) / sizeof(arr[0]) - 1);
for (auto i : arr) {
cout << i << " ";
}
cout << endl;
return 0;
}