-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmergesort.cpp
92 lines (76 loc) · 1.97 KB
/
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
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
89
90
91
92
// {"category": "Sort", "notes": "Mergesort"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <Windows.h>
using namespace std;
//------------------------------------------------------------------------------
//
// Mergesort
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
template<class Object>
void mergesort(Object objects[], Object* pCopy, int start, int end)
{
if (nullptr == pCopy || start >= end)
{
return;
}
int center = (start + end) / 2;
mergesort(objects, pCopy, start, center);
mergesort(objects, pCopy, center + 1, end);
for (int i = start; i <= end; i++)
{
pCopy[i] = objects[i];
}
int left = start;
int right = center + 1;
int index = start;
while (left <= center && right <= end)
{
if (pCopy[left] < pCopy[right])
{
objects[index++] = pCopy[left++];
}
else
{
objects[index++] = pCopy[right++];
}
}
for (int i = left; i <= center; i++)
{
objects[index++] = pCopy[i];
}
}
template<class Object>
void mergesort(Object objects[], int length)
{
if (length > 0)
{
Object* pCopy = new Object[length];
mergesort(objects, pCopy, 0, length - 1);
delete[] pCopy;
}
}
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
int numbers[] = { 13, 81, 92, 43, 65, 31, 57, 26, 75, 0 };
mergesort(numbers, ARRAYSIZE(numbers));
for (int i = 0; i < ARRAYSIZE(numbers); i++)
{
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}