-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.cpp
128 lines (106 loc) · 2.49 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// Test for number of inversions in an input file (value at index = i is greater than value at index > i)
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
// Number of inversions counter
double numInversions = 0;
//Size of input file desired (mostly used for debug to test on smaller subsets)
#define SIZE (100000)
void Merge(int a[], const int low, const int high, int mid)
{
//Clone the array for processing the left and right sides in place before copying back to a[]
int * tmp = new int[high + 1 - low];
//Index for filling the main array
int idx = 0;
//Index for "left" side
int i = low;
//Index for "right" side
int j = mid + 1;
//While both sides still have elements, compare values to merge into temp array
while ((i <= mid) && (j <= high))
{
if (a[i] <= a[j])
{
tmp[idx] = a[i];
i++;
}
else
{
tmp[idx] = a[j];
//If a left side value is added before a right side, then there are inversions related to the number of elements left
numInversions += mid + 1 - i;
j++;
}
idx++;
}
//Only the left side has elements left, fill the temp array with them
while (i <= mid)
{
tmp[idx] = a[i];
i++;
idx++;
}
//Only the right side has elements left, fill the temp array with them
while (j <= high)
{
tmp[idx] = a[j];
j++;
idx++;
}
//Copy the temp array back into a[] before returning to complete the in place merge
for (int p = 0; p <= high-low; p++)
{
a[p + low] = tmp[p];
}
//Clear temporary memory
delete[] tmp;
}
//Recursive function to sort elements
void merge_sort(int a[], int low, int high)
{
int mid;
int inv1 = 0, inv2 = 0, inv3 = 0;
if (low < high)
{
mid = (low + high) / 2;
merge_sort(a, low, mid);
merge_sort(a, mid + 1, high);
Merge(a, low, high, mid);
}
}
//Brute force inversion counter for verification
void BruteForce(int a[])
{
double bruteCnt = 0;
for (int i = 0; i < SIZE - 1; i++)
{
for (int j = i + 1; j < SIZE; j++)
{
if (a[i] > a[j])
bruteCnt++;
}
}
printf("Brute Inversions: %.0f\n", bruteCnt);
}
int _tmain(int argc, _TCHAR* argv[])
{
//Open file to process
ifstream file("C:/Users/sean/Downloads/test.txt", ios::in);
int a[SIZE];
//Create array of elements from the file
int num;
for (int i = 0; i < SIZE; i++)
{
file >> num;
a[i] = num;
}
file.close();
//Brute force to get a test result
BruteForce(a);
//Merge sort the elements and count inversions
merge_sort(a, 0, SIZE-1);
printf("Merge Inversions: %.0f\n", numInversions);
getchar();
return 0;
}