-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountsort.cpp
More file actions
133 lines (99 loc) · 2.95 KB
/
countsort.cpp
File metadata and controls
133 lines (99 loc) · 2.95 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
void printArray(vector<int>& arr){
for (int i = 0; i < arr.size(); i++){
cout << arr[i] << " ";
}
cout << endl;
}
void countSort(vector<int>& arr, long long& operations){
if (arr.empty()) return;
int maxVal = arr[0];
int minVal = arr[0];
for (int i = 1; i < arr.size(); i++){
operations++;
if (arr[i] > maxVal) maxVal = arr[i];
if (arr[i] < minVal) minVal = arr[i];
}
int range = maxVal - minVal + 1;
vector<int> count(range, 0);
vector<int> output(arr.size(), -1);
for (int i = 0; i < arr.size(); i++){ //count array values
count[arr[i] - minVal]++;
operations++;
}
for (int i = 1; i < range; i++){
count[i] += count[i-1];
operations++;
}
cout << "\n Final Count Array (after prefix sum): \n";
cout << "Count: ";
printArray(count);
cout << "\n Output Array (B): \n";
for (int i = arr.size() - 1; i >= 0; i--){
int pos = count[arr[i] - minVal] - 1;
output[pos] = arr[i];
count[arr[i] - minVal]--;
operations++;
cout << "\n Placed " << arr[i] << " at position " << pos << endl;
cout << "B: ";
printArray(output);
cout << "Updated Count: ";
printArray(count);
}
for (int i = 0; i < arr.size(); i++){
arr[i] = output[i];
operations++;
}
}
void processArray(vector<int> arr, char type, int arrayNum, ofstream &fout, long long &sumOps, int& batchCount){
long long operations = 0;
countSort(arr, operations); //array sorted
fout << arrayNum << "," << type << "," << arr.size() << ","
<< operations << endl;
sumOps += operations;
batchCount++;
if (batchCount == 10){
fout << "AVG,AVG," <<arr.size()<<","<<(double)sumOps/10 <<"\n";
batchCount = 0;
sumOps = 0;
}
}
int main(){
ifstream fin("arrays.csv");
ofstream fout("count_results.csv");
if (!fin || !fout){
cout << "file error :/";
return 0;
}
fout << "Array_No,Type,Size,Operations\n";
int arrayNum = 1;
int batchCount = 0;
long long sumOps = 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, sumOps, batchCount);
arrayNum++;
}
fin.close();
fout.close();
cout<<"Count sort completed :)";
return 0;
}