-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sorter.cpp
74 lines (62 loc) · 1.38 KB
/
merge_sorter.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
#include "MergeSorter.h"
#include <iostream>
#include <cstring>
MergeSorter::MergeSorter()
{
//ctor
}
MergeSorter::~MergeSorter()
{
//dtor
}
/**
* Implementation of merge sort in C++
*
* @author Gary Hannah
*/
void MergeSorter::sort(int arr[], const int left, const int right)
{
const int diff = right - left;
/*
* The stopping condition for recursive function calls.
* An array of size 1 is sorted. Now we can return
* and the previous instance of sort() will then merge.
*/
if (1 == diff)
return;
/*
* Split the array into two subsegments
*/
const int mid = (left + right) >> 1;
/*
* Recursively call sort() on subsegments
*/
sort(arr, left, mid);
sort(arr, mid, right);
/*
* Temporary array for merging process
*/
int tmp[diff];
int k = 0, i = left, j = mid;
for ( ; i < mid && j < right; )
{
if (arr[j] < arr[i])
tmp[k++] = arr[j++];
else
tmp[k++] = arr[i++];
}
/*
* Catch the rest that may have been missed
* at the end of one of the subsegments
*/
while (i < mid)
tmp[k++] = arr[i++];
while (j < right)
tmp[k++] = arr[j++];
/*
* Now overwrite subsegment [left:right] with
* the sorted values in tmp[]
*/
std::memcpy(arr + left, tmp, diff * sizeof(int));
return;
}