-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursionMergeSort.cpp
More file actions
63 lines (52 loc) · 1.38 KB
/
Copy pathRecursionMergeSort.cpp
File metadata and controls
63 lines (52 loc) · 1.38 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
using namespace std;
void merge(int *arr, int start, int end) {
int mid = start + (end - start) / 2;
int len1 = mid - start + 1;
int len2 = end - mid;
int *first = new int[len1];
int *second = new int[len2];
int mainArrayIndex = start;
for (int i = 0; i < len1; i++) {
first[i] = arr[mainArrayIndex++];
}
mainArrayIndex = mid + 1;
for (int i = 0; i < len2; i++) {
second[i] = arr[mainArrayIndex++];
}
int index1 = 0, index2 = 0;
mainArrayIndex = start;
while (index1 < len1 && index2 < len2) {
if (first[index1] < second[index2]) {
arr[mainArrayIndex++] = first[index1++];
} else {
arr[mainArrayIndex++] = second[index2++];
}
}
while (index1 < len1) {
arr[mainArrayIndex++] = first[index1++];
}
while (index2 < len2) {
arr[mainArrayIndex++] = second[index2++];
}
delete[] first;
delete[] second;
}
void mergeSort(int *arr, int start, int end) {
if (start >= end) {
return;
}
int mid = start + (end - start) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid + 1, end);
merge(arr, start, end);
}
int main() {
int arr[10] = {5, 6, 4, 1, 0, 9, 2, 7, 8, 3};
int size = 10;
mergeSort(arr, 0,----- size - 1);
for (int i : arr) {
cout << i << " ";
}
return 0;
}