-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab1.cpp
More file actions
218 lines (187 loc) · 7 KB
/
Lab1.cpp
File metadata and controls
218 lines (187 loc) · 7 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <dirent.h>
#include <sys/stat.h>
#include <chrono>
#include <algorithm>
struct Child {
int year;
int groupNumber;
std::string fullName;
std::string birthDate;
int shiftNumber;
bool operator<(const Child& other) const {
if (year != other.year)
return year < other.year;
if (groupNumber != other.groupNumber)
return groupNumber < other.groupNumber;
if (shiftNumber != other.shiftNumber)
return shiftNumber < other.shiftNumber;
return fullName < other.fullName;
}
bool operator>(const Child& other) const {
return other < *this;
}
bool operator<=(const Child& other) const {
return !(other < *this);
}
bool operator>=(const Child& other) const {
return !(*this < other);
}
};
// Функция для чтения строки из CSV файла и преобразования в объект child
Child parseCSVLine(const std::string& line) {
std::stringstream ss(line);
std::string item;
Child child;
std::getline(ss, item, ',');
child.year = std::stoi(item);
std::getline(ss, item, ',');
child.groupNumber = std::stoi(item);
std::getline(ss, child.fullName, ',');
std::getline(ss, child.birthDate, ',');
std::getline(ss, item, ',');
child.shiftNumber = std::stoi(item);
return child;
}
// Функция для чтения из файла CSV и создания вектора объектов child
std::vector<Child> readChildrenFromFile(const std::string& filename) {
std::vector<Child> children;
std::ifstream file(filename);
std::string line;
while (std::getline(file, line)) {
if (!line.empty()) {
children.push_back(parseCSVLine(line));
}
}
return children;
}
// Функция для записи в файл CSV вектора объектов child
void writeChildrenToFile(const std::string& filename, const std::vector<Child>& children) {
std::ofstream file(filename);
for (const auto& child : children) {
file << child.year << ","
<< child.groupNumber << ","
<< child.fullName << ","
<< child.birthDate << ","
<< child.shiftNumber << "\n";
}
}
// Функция сортировки выбором
void selectionSort(std::vector<Child>& arr) {
size_t n = arr.size();
for (size_t i = 0; i < n - 1; ++i) {
size_t minIdx = i;
for (size_t j = i + 1; j < n; ++j) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
std::swap(arr[i], arr[minIdx]);
}
}
// Функция сортировки простыми вставками
void insertionSort(std::vector<Child>& arr) {
size_t n = arr.size();
for (size_t i = 1; i < n; ++i) {
Child key = arr[i];
int j = i - 1;
while (j >= 0 && key < arr[j]) {
arr[j + 1] = arr[j];
--j;
}
arr[j + 1] = key;
}
}
// Функция шейкер-сортировки
void shakerSort(std::vector<Child>& arr) {
size_t left = 0;
size_t right = arr.size() - 1;
while (left < right) {
for (size_t i = left; i < right; ++i) {
if (arr[i] > arr[i + 1]) {
std::swap(arr[i], arr[i + 1]);
}
}
--right;
for (size_t i = right; i > left; --i) {
if (arr[i] < arr[i - 1]) {
std::swap(arr[i], arr[i - 1]);
}
}
++left;
}
}
// Функция для измерение времени
template <typename Func>
long long measureSortTime(std::vector<Child>& children, Func sortFunc) {
auto start = std::chrono::high_resolution_clock::now();
sortFunc(children);
auto end = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
}
// Функция для записи в файл CSV времени, затраченного на сортировку
void writeTimesToFile(const std::string& filename, const std::vector<std::pair<std::string, long long>>& times) {
std::ofstream file(filename);
for (const auto& [name, time] : times) {
file << name << "," << time << "\n";
}
}
// Функция для проверки того, что строка заканчивается на ".csv"
bool hasCSVExtension(const std::string& filename) {
return filename.size() >= 4 &&
filename.substr(filename.size() - 4) == ".csv";
}
// Функция для создания директории (если она не существует)
void createDirectoryIfNotExists(const std::string& dirname) {
struct stat st{};
if (stat(dirname.c_str(), &st) != 0) {
mkdir(dirname.c_str(), 0755);
}
}
int main() {
std::string inputDir = "children-unsorted";
std::string outputBase = "children-sorted";
createDirectoryIfNotExists(outputBase);
createDirectoryIfNotExists(outputBase + "/times");
DIR* dir = opendir(inputDir.c_str());
if (!dir) {
std::cerr << "Не удалось открыть директорию: " << inputDir << "\n";
return 1;
}
dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
std::string filename = entry->d_name;
// Проверяем, что entry это файл, и что он имеет расширение CSV
if (entry->d_type == DT_REG && hasCSVExtension(filename)) {
std::string inputPath = inputDir + "/" + filename;
std::vector<Child> original = readChildrenFromFile(inputPath);
std::vector<std::pair<std::string, long long>> times;
// Создаем вектор пар вида <строка, функция>, в котором лежат наши сортировки
std::vector<std::pair<std::string, void(*)(std::vector<Child>&)>> sorters = {
{"SelectionSort", selectionSort},
{"InsertionSort", insertionSort},
{"ShakerSort", shakerSort},
{"StdSort", [](std::vector<Child>& d) { std::sort(d.begin(), d.end()); }}
};
for (const auto& [sortName, sortFunc] : sorters) {
std::vector<Child> sorted = original;
// Сортируем
long long time = measureSortTime(sorted, sortFunc);
std::string sortDir = outputBase + "/" + sortName;
createDirectoryIfNotExists(sortDir);
std::string outputPath = sortDir + "/" + filename;
writeChildrenToFile(outputPath, sorted);
times.emplace_back(sortName, time);
}
// Сохраняем файл с результатами времени
std::string timeFile = outputBase + "/times/" + filename;
writeTimesToFile(timeFile, times);
}
}
closedir(dir);
return 0;
}