-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_sort.cpp
88 lines (80 loc) · 2.05 KB
/
merge_sort.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
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 <cstddef>
#include <iostream>
#include <memory>
using std::cout;
template < typename T >
void merge(T *arr, T *tempArr, size_t left, size_t mid, size_t right)
{
// unsorted elems index in left part
size_t l_pos = left;
// unsorted elems index in right part
size_t r_pos = mid + 1;
// tempArr index
size_t pos = left;
// if there are emels in left part and right part
while (l_pos <= mid and r_pos <= right)
{
// compare two parts elems at the front, and insert the smaller into
// tempArr
if (arr[l_pos] <= arr[r_pos])
{
tempArr[pos++] = arr[l_pos++];
} else
{
tempArr[pos++] = arr[r_pos++];
}
}
// merge remaining elems
// because we begin merging with single elem, so all parts are already
// sorted. When the left part is empty, then, just merge remaining right
// elems after.
while (l_pos <= mid)
{
tempArr[pos++] = arr[l_pos++];
}
while (r_pos <= right)
{
tempArr[pos++] = arr[r_pos++];
}
// cover origin arr
while (left <= right)
{
arr[left] = tempArr[left];
++left;
}
}
template < typename T >
void partition(T *arr, T *tempArr, size_t left, size_t right)
{
if (left < right)
{
size_t mid = left + (right - left) / 2;
// recursion divide left part
partition(arr, tempArr, left, mid);
// recursion divide right part
partition(arr, tempArr, mid + 1, right);
// merge sorted parts
merge(arr, tempArr, left, mid, right);
}
}
template < typename T > void merge_sort(T *arr, size_t len)
{
// create a assistant array
std::unique_ptr< T[] > tempArr = std::make_unique< T[] >(len);
partition(arr, tempArr.get(), 0, len - 1);
}
int *test()
{
std::unique_ptr< int[] > arr(new int[]{3, 5, 7, 6, 8, 9, 4});
merge_sort(arr.get(), 7);
for (int i = 0; i < 7; ++i)
{
cout << arr[i] << ' ';
}
return arr.get();
}
int main()
{
int *ptr = test();
cout << "test";
}