forked from D3VILx0/Open-Source-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.cpp
More file actions
88 lines (77 loc) · 1.87 KB
/
Copy pathMergeSort.cpp
File metadata and controls
88 lines (77 loc) · 1.87 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
class MergeSort
{
public:
void merge(int Arr[], int begin, int mid, int end)
{
int rightLen = mid - begin + 1;
int leftLen = end - mid;
int *rightArr = new int[rightLen];
int *leftArr = new int[leftLen];
for (int i = 0; i < rightLen; i++)
{
rightArr[i] = Arr[begin + i];
}
for (int j = 0; j < leftLen; j++)
{
leftArr[j] = Arr[mid + 1 + j];
}
int rIndex = 0;
int lIndex = 0;
int ArrIndex = begin;
while (rIndex < rightLen && lIndex < leftLen)
{
if (rightArr[rIndex] <= leftArr[lIndex])
{
Arr[ArrIndex] = rightArr[rIndex];
rIndex++;
}
else
{
Arr[ArrIndex] = leftArr[lIndex];
lIndex++;
}
ArrIndex++;
}
while (rIndex < rightLen)
{
Arr[ArrIndex] = rightArr[rIndex];
ArrIndex++;
rIndex++;
}
while (lIndex < leftLen)
{
Arr[ArrIndex] = leftArr[lIndex];
ArrIndex++;
lIndex++;
}
delete[] leftArr;
delete[] rightArr;
}
void mergeSort(int Arr[], int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(Arr, l, m);
mergeSort(Arr, m + 1, r);
merge(Arr, l, m, r);
}
}
void displayArr(int Arr[], int len)
{
for (int i = 0; i < len; i++)
{
std::cout << Arr[i] << " ";
}
}
};
int main()
{
MergeSort mergeSortObj;
int Arr[] = {11, 7, 6, 8, 8, 9, 5, 9, 6, 5, 4};
int len = sizeof(Arr) / sizeof(Arr[0]);
mergeSortObj.mergeSort(Arr, 0, len - 1);
mergeSortObj.displayArr(Arr, len);
return 0;
}