Repository navigation
Expand file tree
/
Copy pathK2L3.cpp
More file actions
221 lines (195 loc) · 7.21 KB
/
Copy pathK2L3.cpp
File metadata and controls
221 lines (195 loc) · 7.21 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
219
220
221
#include <iostream>
#include <algorithm>
#include <ctime>
#include <fstream>
#include <chrono>
#include <iomanip>
//Выводит элементы массива seq размера size в квадратных скобках
void printSequence(int* seq, int size) {
std::cout << "[";
for (int i = 0; i < size - 1; i++) {
if (seq[i] == INT_MAX) {
std::cout << "INT_MAX" << ", ";
} else {
std::cout << seq[i] << ", ";
}
}
if (seq[size - 1] == INT_MAX) {
std::cout << "INT_MAX" << "]\n";
} else {
std::cout << seq[size - 1] << "]\n";
}
}
int* generateRandomSequence(int size) {
int* arr = new int[size]; //Выделение памяти
for (int i = 0; i < size; i++)
arr[i] = rand(); //Заполнение массива
return arr;
}
int* generateIncreaseSequence(int size) {
int* arr = new int[size]; //Выделение памяти
int step = INT_MAX / size; // Вычисление шага
for (int i = 0; i < size; i++)
arr[i] = i * step + rand() % step; //Заполнение массива
return arr;
}
int* generateDecreaseSequence(int size) {
int* arr = new int[size]; //Выделение памяти
int step = INT_MAX / size; // Вычисление шага
for (int i = size - 1; i >= 0; i--)
arr[i] = (size - i - 1) * step + rand() % step; //Заполнение массива
return arr;
}
void Selection_Sort(int* arr, int arrSize, bool fullPrint = false, int* compareCount = NULL, int* transposeCount = NULL) {
(*compareCount) = 0;
if (fullPrint) {
(*compareCount)++;
for (int i = 0; i < arrSize - 1; i++) {
(*compareCount)++;
//находим номер минимального значения
int min = i;
(*compareCount)++;
for (int j = i + 1; j < arrSize; j++) {
(*compareCount)++;
(*compareCount)++;
//значение первой неотсортированной позиции
if (arr[j] < arr[min]) {
min = j;
}
}
(*transposeCount)++;
//производим обмен
std::swap(arr[i], arr[min]);
printSequence(arr, arrSize);
}
} else {
(*compareCount)++;
for (int i = 0; i < arrSize - 1; i++) {
(*compareCount)++;
int min = i;
(*compareCount)++;
for (int j = i + 1; j < arrSize; j++) {
(*compareCount)++;
(*compareCount)++;
if (arr[j] < arr[min]) {
min = j;
}
}
(*transposeCount)++;
std::swap(arr[i], arr[min]);
}
}
}
int Partition(int* arr, int left, int right, int* compareCount = NULL, int* transposeCount = NULL) {
int middle = (left + right) / 2;
(*transposeCount)++;
std::swap(arr[middle], arr[right]);
int q = left;
(*compareCount)++;
for (int u = left; u <= right - 1; u++) {
(*compareCount)++;
(*compareCount)++;
if (arr[u] <= arr[right]) {
(*transposeCount)++;
std::swap(arr[u], arr[q]);
q++;
}
}
(*transposeCount)++;
std::swap(arr[q], arr[right]);
return q;
}
// another draft
void Quick_Sort(int* arr, int left, int right, bool fullPrint = false, int maxSize = -1, int* compareCount = NULL, int* transposeCount = NULL) {
if (fullPrint) {
(*compareCount)++;
if (left < right) {
int middle = Partition(arr, left, right, compareCount, transposeCount);
printSequence(arr, maxSize);
Quick_Sort(arr, left, middle - 1, fullPrint, maxSize, compareCount, transposeCount);
Quick_Sort(arr, middle + 1, right, fullPrint, maxSize, compareCount, transposeCount);
}
} else {
(*compareCount)++;
if (left < right) {
int middle = Partition(arr, left, right, compareCount, transposeCount);
Quick_Sort(arr, left, middle - 1, fullPrint, maxSize, compareCount, transposeCount);
Quick_Sort(arr, middle + 1, right, fullPrint, maxSize, compareCount, transposeCount);
}
}
}
template <typename ... Types>
long long timeTest(void (*function)(Types ... args), Types ... args) {
auto beginTime = std::chrono::steady_clock::now();
function(args...);
auto endTime = std::chrono::steady_clock::now();
auto elapsedMs = std::chrono::duration_cast<std::chrono::nanoseconds>(endTime - beginTime).count();
return elapsedMs;
}
int main() {
//Инициализация рандомизатора
srand(time(NULL));
//Производим первичные замеры. Тест на работоспособность алгоритмов
const int smallSize = 15;
std::cout << "TEST FOR SIZE: " << smallSize << std::endl;
int* firstSequence = generateRandomSequence(smallSize);
int* secondSequence = new int[smallSize];
std::copy(firstSequence, firstSequence + smallSize, secondSequence);
printSequence(firstSequence, smallSize);
int compareCount = 0;
int transposeCount = 0;
Selection_Sort(firstSequence, smallSize, true, &compareCount, &transposeCount);
std::cout << "Selection_Sort. compareCount: " << compareCount << " transposeCount: " << transposeCount << std::endl;
std::cout << std::endl;
printSequence(secondSequence, smallSize);
compareCount = 0;
transposeCount = 0;
Quick_Sort(secondSequence, 0, smallSize - 1, true, smallSize, &compareCount, &transposeCount);
std::cout << "Quick_Sort. compareCount: " << compareCount << " transposeCount: " << transposeCount << std::endl;
delete[] firstSequence;
delete[] secondSequence;
int seqCount = 3;
const char* seqNames[] = { "Sorts.csv", "Sorts_increase.csv", "Sorts_decrease.csv" };
//Функции генерации последовательностей
int* (*seqFuncs[]) (int) = {
generateRandomSequence,
generateIncreaseSequence,
generateDecreaseSequence
};
for (int k = 0; k < seqCount; k++) {
//Открываем файл с нужным названием
std::ofstream file(seqNames[k]);
//Печать шапки
file << "count" << ';'
<< "Selection_sort_compareCount" << ';'
<< "Selection_sort_transposeCount" << ';'
<< "Selection_sort_time" << ';'
<< "Quick_sort_compareCount" << ';'
<< "Quick_sort_transposeCount" << ';'
<< "Quick_sort_time" << '\n';
std::cout << seqNames[k] << std::endl;
//полноразмерное тестирование
for (int i = 1000; i <= 100000; i += 1000) {
//Количество элементов массива - степень десяти
// Создаём две одинаковые последовательности
firstSequence = seqFuncs[k](i);
secondSequence = new int[i];
std::copy(firstSequence, firstSequence + i, secondSequence);
//Сбрасываем счётчики и замеряем время
compareCount = 0;
transposeCount = 0;
auto time = timeTest(Selection_Sort, firstSequence, i, false, &compareCount, &transposeCount);
//Выводим в файл
file << i << ';' << compareCount << ';' << transposeCount << ';' << time << ';';
compareCount = 0;
transposeCount = 0;
time = timeTest(Quick_Sort, secondSequence, 0, i - 1, false, i, &compareCount, &transposeCount);
file << i << ';' << compareCount << ';' << transposeCount << ';' << time << '\n';
//Удаляем последовательности
delete[] firstSequence;
delete[] secondSequence;
std::cout << "Loop for " << i << " complete" << std::endl;
}
file.close();
}
}