-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergesort.cpp
More file actions
117 lines (92 loc) · 2.59 KB
/
mergesort.cpp
File metadata and controls
117 lines (92 loc) · 2.59 KB
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
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
void merge(vector<int>& arr, int left, int mid, int right, long long& comparisons){
int n1 = mid - left + 1;
int n2 = right - mid;
vector<int> L(n1), R(n2);
for (int i = 0; i < n1; i++){
L[i] = arr[left + i];
}
for (int j = 0; j < n2; j++){
R[j] = arr[mid + 1 + j];
}
int i = left, j = mid +1, k = left;
while (i <= n1 && j <= n2){
comparisons++;
if (L[i] <= R[j]){
arr[k] = L[i];
i++;
} else{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1){
arr[k] = L[i];
i++, k++;
}
while (j < n2){
arr[k] = R[j];
j++, k++;
}
}
void mergeSort(vector<int>& arr, int left, int right, long long& comparisons){
if (left < right){
int mid = left + (right-left)/2;
mergeSort(arr, left, mid, comparisons);
mergeSort(arr, mid+1, right, comparisons);
merge(arr, left, mid, right, comparisons);
}
}
void processArray(vector<int> arr, char type, int arrayNum, ofstream &fout, long long &sumCom, int& batchCount){
long long comparisons = 0;
mergeSort(arr, 0, arr.size()-1, comparisons); //array sorted
fout << arrayNum << "," << type << "," << arr.size() << ","
<<comparisons << endl;
sumCom += comparisons;
batchCount++;
if (batchCount == 10){
fout << "AVG,AVG," <<arr.size()<<","<<(double)sumCom/10 <<"\n";
batchCount = 0;
sumCom = 0;
}
}
int main(){
ifstream fin("arrays.csv");
ofstream fout("merge_results.csv");
if (!fin || !fout){
cout << "file error :/";
return 0;
}
fout << "Array_No,Type,Size,Comparisons\n";
int arrayNum = 1;
int batchCount = 0;
long long sumCom = 0;
while (true){
vector<int> arr;
char type; int size;
int number;
char comma;
if (!(fin >> type >> comma >> size >> comma)) break;
while (fin>>number){
arr.push_back(number);
if (fin.peek() == ','){
fin.ignore();
} else{
break;
}
}
char ch;
while (fin.get(ch) && ch != '\n');
processArray(arr, type, arrayNum, fout, sumCom, batchCount);
arrayNum++;
}
fin.close();
fout.close();
cout<<"Merge sort completed :)";
return 0;
}