-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge.hpp
56 lines (49 loc) · 1.28 KB
/
merge.hpp
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
void merge(int *array, int mid, int end)
{
int tempBegin = 0;
mid++;
int tempMid = mid;
int *mergedArray = new int[end + 1];
end++;
int mergedArrayIndex = 0;
while (tempBegin < mid || tempMid < end)
{
if (tempBegin < mid && tempMid < end)
{
if (array[tempBegin] <= array[tempMid])
{
mergedArray[mergedArrayIndex] = array[tempBegin];
tempBegin++;
}
else
{
mergedArray[mergedArrayIndex] = array[tempMid];
tempMid++;
}
}
else if (tempBegin < mid)
{
mergedArray[mergedArrayIndex] = array[tempBegin++];
}
else if (tempMid < end)
{
mergedArray[mergedArrayIndex] = array[tempMid++];
}
mergedArrayIndex++;
}
for (size_t i = 0; i < end; i++)
{
array[i] = mergedArray[i];
}
}
void mergeSort(int array[], int begin, int end)
{
if (begin >= end)
return;
auto mid = begin + (end - begin) / 2;
mergeSort(array, begin, mid);
mergeSort(array, mid + 1, end);
mid = mid - begin;
end = end - begin;
merge(&array[begin], mid, end);
}