-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlgorithm.cpp
More file actions
738 lines (624 loc) · 26.8 KB
/
Algorithm.cpp
File metadata and controls
738 lines (624 loc) · 26.8 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
#include <iostream>
#include <vector>
#include <thread>
#include <chrono>
#include <random>
#include <string>
#include <functional>
#include <algorithm>
#include <queue>
#include <bits/stdc++.h>
#include <stdexcept>
#include "json.hpp"
#include <barrier>
// ===================== Measurement =====================
class Measurement {
public:
double threadCount, duration, dataSize;
long long start, end;
bool correct;
bool* iterative;
Measurement(double threadCount, double duration, double dataSize, long long start, long long end, bool correct, bool* iterative = nullptr)
: threadCount(threadCount), duration(duration), dataSize(dataSize), start(start), end(end), correct(correct), iterative(iterative) {}
Measurement() = default;
[[nodiscard]] std::string toString() const {
if (iterative != nullptr) {
return "Thread Count: " + std::to_string(threadCount) +
", Duration: " + std::to_string(duration) +
", Data Size: " + std::to_string(dataSize) +
", Is algorithm correct?: " + std::to_string(correct) +
", Is iterative?: " + std::to_string(*iterative);
}
return "Thread Count: " + std::to_string(threadCount) +
", Duration: " + std::to_string(duration) +
", Data Size: " + std::to_string(dataSize) +
", Is algorithm correct?: " + std::to_string(correct);
}
[[nodiscard]] nlohmann::json toJson() const {
nlohmann::json j;
j["duration"] = duration;
// j["start"] = start;
// j["end"] = end;
j["correct"] = correct;
if (iterative != nullptr) {
j["iterative"] = *iterative;
} else {
j["iterative"] = false;
}
return j;
}
bool operator==(const Measurement & measurement) const {
return threadCount == measurement.threadCount &&
duration == measurement.duration &&
dataSize == measurement.dataSize &&
start == measurement.start &&
end == measurement.end &&
correct == measurement.correct;
}
Measurement &operator+=(const Measurement & result) {
// add the values of the result to the current object
duration += result.duration;
return *this;
}
};
// ===================== Algorithm =====================
class Algorithm {
protected:
int threadCount;
long long dataSize;
bool verbose = false;
bool* reiterative;
public:
Algorithm(int threadCount, long long dataSize, bool verbose, bool* reiterative = nullptr)
: threadCount(threadCount), dataSize(dataSize), verbose(verbose), reiterative(reiterative) {}
virtual ~Algorithm() = default;
std::vector<int*> executeTask(const std::vector<long long>& areaOfResponsibility, const std::vector<int*>& data,
std::atomic<bool>& stopFlag, std::barrier<> & sync_point, int thread_id = 0) {
if (verbose) {
std::cout << "Thread " << thread_id << " awaiting execution start." << std::endl;
}
sync_point.arrive_and_wait();
if (verbose) {
std::cout << "Thread " << thread_id << " starting execution." << std::endl;
}
return execute(areaOfResponsibility, data, stopFlag);
}
virtual void cleanupData(std::vector<int*>& data, std::vector<std::vector<int*>>& result) const = 0;
Measurement executeAndMeasure(int threads, long long dataSize) {
if (threads <= 0 || dataSize <= 0) {
throw std::invalid_argument("Threads and data size must be greater than zero.");
}
if (verbose) {
std::cout << "Starting execution with " << threads << " threads and data size " << dataSize << "." << std::endl;
}
std::vector<int*> data = generateData(dataSize);
std::vector<std::thread> threadPool;
std::vector<std::vector<int*>> result(threads);
std::atomic<bool> stopFlag = false;
auto start = std::chrono::high_resolution_clock::now();
std::barrier sync_point(threadCount);
try {
for (int i = 0; i < threads; ++i) {
auto areaOfResponsibility = calculate_area_of_responsibility(i, threads, dataSize);
if (verbose) {
std::cout << "Thread " << i << " responsible for rows [" << areaOfResponsibility[0] << ", "
<< areaOfResponsibility[1] << "]." << std::endl;
}
threadPool.emplace_back([&, i, areaOfResponsibility]() {
try {
if (!stopFlag) {
result[i] = executeTask(areaOfResponsibility, data, stopFlag, sync_point, i);
}
if (verbose && stopFlag) {
std::lock_guard<std::mutex> lock(outputMutex);
std::cout << "Thread " << i << " stopped early." << std::endl;
}
} catch (const std::exception& e) {
std::cerr << "Thread " << i << " encountered an exception: " << e.what() << std::endl;
}
});
}
for (auto& t : threadPool) {
if (t.joinable()) {
t.join();
}
}
auto final_result = concat_results(result, data, threads, dataSize);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start;
bool results_are_correct = test_result(data, final_result, dataSize);
if (verbose) {
std::cout << "Execution completed in " << duration.count() << " seconds. Results are "
<< (results_are_correct ? "correct." : "incorrect.") << std::endl;
}
cleanupData(data, result);
return Measurement(
static_cast<double>(threads),
duration.count(),
static_cast<double>(dataSize),
start.time_since_epoch().count(),
end.time_since_epoch().count(),
results_are_correct,
reiterative
);
} catch (const std::exception& e) {
std::cerr << "Exception during execution: " << e.what() << std::endl;
cleanupData(data, result);
throw;
}
}
virtual std::string getType() const = 0;
protected:
std::mutex outputMutex; // For synchronizing output
virtual std::vector<int*> execute(const std::vector<long long>& area_of_responsibility, const std::vector<int*>& inputData, std::atomic<bool>& stopFlag) = 0;
virtual std::vector<int*> generateData(long long dataSize) = 0;
virtual std::vector<long long> calculate_area_of_responsibility(int currentThread, int maxThreads, long long dataSize) = 0;
virtual bool test_result(const std::vector<int*>& input_data, const std::vector<int*>& result, long long dataSize) = 0;
virtual std::vector<int*> concat_results(const std::vector<std::vector<int*>>& partial_results, const std::vector<int*>& inputData, int thread_count, long long data_size) = 0;
};
// ===================== SortingAlgorithm =====================
class SortingAlgorithm : public Algorithm {
public:
SortingAlgorithm(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: Algorithm(threadCount, dataSize, verbose, reiterative) {}
[[nodiscard]] std::string getType() const override {
return "SortingAlgorithm";
}
protected:
void cleanupData(std::vector<int*>& data, std::vector<std::vector<int*>>& result) const override {
if (!data.empty() && data[0] != nullptr) {
delete[] data[0]; // Deallocate the main array
data[0] = nullptr;
}
for (auto& partial_result : result) {
if (!partial_result.empty() && partial_result[0] != nullptr) {
delete[] partial_result[0]; // Deallocate each partial result
partial_result[0] = nullptr;
}
}
result.clear();
data.clear();
}
std::vector<int*> concat_results(const std::vector<std::vector<int*>>& partial_results, const std::vector<int*>& inputData, int thread_count, long long data_size) override {
if (verbose) {
std::cout << "Merging partial results from threads." << std::endl;
}
// Allocate space for the merged data
auto* merged_data = new int[data_size];
std::vector<long long> start(thread_count), end(thread_count), indexes(thread_count);
for (int i = 0; i < thread_count; ++i) {
auto area_of_responsibility = calculate_area_of_responsibility(i, thread_count, data_size);
start[i] = area_of_responsibility[0];
end[i] = area_of_responsibility[1];
indexes[i] = start[i];
}
int merged_index = 0;
while (true) {
int min_value = INT_MAX;
int min_index = -1;
// Find the smallest element among the threads
for (int i = 0; i < thread_count; ++i) {
if (indexes[i] < end[i] && inputData[0][indexes[i]] < min_value) {
min_value = inputData[0][indexes[i]];
min_index = i;
}
}
if (min_index == -1) break; // No more elements to merge
merged_data[merged_index++] = min_value;
indexes[min_index]++;
}
if (verbose) {
std::cout << "Merged data successfully." << std::endl;
}
return {merged_data}; // Return the merged data
}
bool test_result(const std::vector<int*>& input_data, const std::vector<int*>& result, long long dataSize) override {
const int* sorted_data = result[0]; // Assuming the sorted result is stored in the first element
for (long long i = 1; i < dataSize; ++i) {
if (sorted_data[i - 1] > sorted_data[i]) {
std::cout << "Sorting failed at index " << i << ": " << sorted_data[i - 1] << " > " << sorted_data[i] << std::endl;
return false;
}
}
return true;
}
std::vector<int*> execute(const std::vector<long long>& area_of_responsibility, const std::vector<int*>& inputData, std::atomic<bool>& stopFlag) override {
int* data = inputData[0]; // Access the data
long long start = area_of_responsibility[0];
long long end = area_of_responsibility[1];
sortSegment(data, start, end);
return {}; // Sorting is in-place; no need to return data here
}
std::vector<int*> generateData(long long dataSize) override {
auto* data = new int[dataSize]; // Dynamically allocate array
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 1000);
for (long long i = 0; i < dataSize; ++i) {
data[i] = dis(gen);
}
return {data}; // Return the generated data as a vector containing a pointer
}
std::vector<long long> calculate_area_of_responsibility(int currentThread, int maxThreads, long long dataSize) override {
long long segmentSize = dataSize / maxThreads;
return {currentThread * segmentSize, (currentThread == maxThreads - 1) ? dataSize : (currentThread + 1) * segmentSize};
}
virtual void sortSegment(int* data, long long start, long long end) = 0;
};
// ===================== Algorithms =====================
class BubbleSort : public SortingAlgorithm {
public:
BubbleSort(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: SortingAlgorithm(threadCount, dataSize, verbose, reiterative) {}
[[nodiscard]] std::string getType() const override {
return "BubbleSort";
}
protected:
void sortSegment(int* data, long long start, long long end) override {
for (long long i = start; i < end - 1; ++i) {
for (long long j = start; j < end - 1 - (i - start); ++j) {
if (data[j] > data[j + 1]) {
std::swap(data[j], data[j + 1]);
}
}
}
}
};
class QuickSort : public SortingAlgorithm {
public:
QuickSort(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: SortingAlgorithm(threadCount, dataSize, verbose, reiterative) {}
[[nodiscard]] std::string getType() const override {
return "QuickSort";
}
protected:
void sortSegment(int* data, long long start, long long end) override {
std::sort(data + start, data + end);
}
};
class MergeSort : public SortingAlgorithm {
public:
MergeSort(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: SortingAlgorithm(threadCount, dataSize, verbose, reiterative) {}
[[nodiscard]] std::string getType() const override {
return "MergeSort";
}
protected:
void sortSegment(int* data, long long start, long long end) override {
if (end - start <= 1) return;
long long mid = start + (end - start) / 2;
sortSegment(data, start, mid);
sortSegment(data, mid, end);
// Temporary array for merging
std::vector<int> temp(end - start);
std::merge(data + start, data + mid, data + mid, data + end, temp.begin());
std::copy(temp.begin(), temp.end(), data + start);
}
};
class InsertionSort : public SortingAlgorithm {
public:
InsertionSort(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: SortingAlgorithm(threadCount, dataSize, verbose, reiterative) {}
[[nodiscard]] std::string getType() const override {
return "InsertionSort";
}
protected:
void sortSegment(int* data, long long start, long long end) override {
for (long long i = start + 1; i < end; ++i) {
int key = data[i];
long long j = i - 1;
while (j >= start && data[j] > key) {
data[j + 1] = data[j];
--j;
}
data[j + 1] = key;
}
}
};
class SelectionSort : public SortingAlgorithm {
public:
SelectionSort(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: SortingAlgorithm(threadCount, dataSize, verbose, reiterative) {}
[[nodiscard]] std::string getType() const override {
return "SelectionSort";
}
protected:
void sortSegment(int* data, long long start, long long end) override {
for (long long i = start; i < end - 1; ++i) {
long long minIndex = i;
for (long long j = i + 1; j < end; ++j) {
if (data[j] < data[minIndex]) {
minIndex = j;
}
}
std::swap(data[i], data[minIndex]);
}
}
};
class HeapSort : public SortingAlgorithm {
public:
HeapSort(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: SortingAlgorithm(threadCount, dataSize, verbose, reiterative) {}
[[nodiscard]] std::string getType() const override {
return "HeapSort";
}
protected:
void sortSegment(int* data, long long start, long long end) override {
std::vector<int> tempData(data + start, data + end);
for (long long i = (end - start - 1) / 2; i >= 0; --i) {
heapify(tempData, tempData.size(), i);
}
for (long long i = tempData.size() - 1; i > 0; --i) {
std::swap(tempData[0], tempData[i]);
heapify(tempData, i, 0);
}
// printVector(tempData);
for (long long i = 0; i < tempData.size(); ++i) {
data[start + i] = tempData[i];
}
}
void heapify(std::vector<int>& data, long long n, long long i) {
long long largest = i;
long long left = 2 * i + 1;
long long right = 2 * i + 2;
if (left < n && data[left] > data[largest]) {
largest = left;
}
if (right < n && data[right] > data[largest]) {
largest = right;
}
if (largest != i) {
std::swap(data[i], data[largest]);
heapify(data, n, largest); // Continue to heapify the subtree
}
}
};
class MatrixOperationAlgorithm : public Algorithm {
public:
MatrixOperationAlgorithm(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: Algorithm(threadCount, dataSize, verbose, reiterative) {}
[[nodiscard]] std::string getType() const override {
return "MatrixOperationAlgorithm";
}
protected:
void cleanupData(std::vector<int*>& data, std::vector<std::vector<int*>>& result) const override {
for (auto& row : data) {
delete[] row;
}
data.clear();
for (auto& partial_result : result) {
for (auto& row : partial_result) {
delete[] row;
}
}
result.clear();
}
std::vector<int*> generateData(long long dataSize) override {
std::vector<int*> matrix(dataSize);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 100);
for (long long i = 0; i < dataSize; ++i) {
matrix[i] = new int[dataSize];
for (long long j = 0; j < dataSize; ++j) {
matrix[i][j] = dis(gen);
}
}
return matrix;
}
std::vector<long long> calculate_area_of_responsibility(int currentThread, int maxThreads, long long dataSize) override {
long long segmentSize = dataSize / maxThreads;
return {currentThread * segmentSize, (currentThread == maxThreads - 1) ? dataSize : (currentThread + 1) * segmentSize};
}
std::vector<int*> execute(const std::vector<long long>& area_of_responsibility, const std::vector<int*>& inputData, std::atomic<bool>& stopFlag) override {
std::vector<int*> partialResult;
for (long long i = area_of_responsibility[0]; i < area_of_responsibility[1]; ++i) {
partialResult.push_back(processRow(inputData[i], inputData));
}
return partialResult;
}
bool test_result(const std::vector<int*>& input_data, const std::vector<int*>& result, long long dataSize) override {
for (long long i = 0; i < dataSize; ++i) {
auto expected = processRow(input_data[i], input_data);
for (long long j = 0; j < dataSize; ++j) {
if (expected[j] != result[i][j]) {
return false;
}
}
}
return true;
}
std::vector<int*> concat_results(const std::vector<std::vector<int*>>& partial_results, const std::vector<int*>& inputData, int thread_count, long long data_size) override {
std::vector<int*> finalMatrix(data_size);
for (int i = 0; i < thread_count; ++i) {
auto area = calculate_area_of_responsibility(i, thread_count, data_size);
for (long long j = area[0]; j < area[1]; ++j) {
finalMatrix[j] = partial_results[i][j - area[0]];
if (verbose) {
// print this row
std::cout << "Row " << j << ": ";
}
}
}
return finalMatrix;
}
virtual int* processRow(const int* row, const std::vector<int*>& matrix) = 0;
};
class MatrixMultiplication : public MatrixOperationAlgorithm {
public:
MatrixMultiplication(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: MatrixOperationAlgorithm(threadCount, dataSize, verbose, reiterative) {}
protected:
int* processRow(const int* row, const std::vector<int*>& matrix) override {
long long size = matrix.size();
int* result = new int[size];
std::fill(result, result + size, 0);
for (long long col = 0; col < size; ++col) {
for (long long k = 0; k < size; ++k) {
result[col] += row[k] * matrix[k][col];
}
}
return result;
}
};
class MatrixAddition : public MatrixOperationAlgorithm {
public:
MatrixAddition(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: MatrixOperationAlgorithm(threadCount, dataSize, verbose, reiterative) {}
protected:
int* processRow(const int* row, const std::vector<int*>& matrix) override {
long long size = matrix.size();
int* result = new int[size];
for (long long col = 0; col < size; ++col) {
result[col] = row[col] + matrix[col][col];
}
return result;
}
};
class MatrixTransposition : public MatrixOperationAlgorithm {
public:
MatrixTransposition(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: MatrixOperationAlgorithm(threadCount, dataSize, verbose, reiterative) {}
protected:
int* processRow(const int* row, const std::vector<int*>& matrix) override {
long long size = matrix.size();
int* result = new int[size];
long long rowIndex = std::distance(matrix.begin(), std::find(matrix.begin(), matrix.end(), row));
for (long long col = 0; col < size; ++col) {
result[col] = matrix[col][rowIndex];
}
return result;
}
};
class SearchAlgorithms : public Algorithm {
protected:
int targetNumber;
std::atomic<bool> found;
std::atomic<long long> foundIndex;
public:
SearchAlgorithms(int threadCount, long long dataSize, bool verbose = false, bool* reiterative = nullptr)
: Algorithm(threadCount, dataSize, verbose, reiterative), found(false), foundIndex(-1) {}
[[nodiscard]] virtual std::string getType() const override = 0;
protected:
std::vector<int*> generateData(long long dataSize) override {
auto* data = new int[dataSize];
for (long long i = 0; i < dataSize; ++i) {
data[i] = i + 1;
}
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<long long> indexDis(0, dataSize - 1);
long long targetIndex = indexDis(gen);
targetNumber = data[targetIndex];
if (verbose) {
std::lock_guard<std::mutex> lock(outputMutex);
std::cout << "Target number: " << targetNumber << " placed at index: " << targetIndex << std::endl;
}
return {data};
}
std::vector<long long> calculate_area_of_responsibility(int currentThread, int maxThreads, long long dataSize) override {
long long segmentSize = dataSize / maxThreads;
return {currentThread * segmentSize, (currentThread == maxThreads - 1) ? dataSize : (currentThread + 1) * segmentSize};
}
std::vector<int*> execute(const std::vector<long long>& area_of_responsibility, const std::vector<int*>& inputData, std::atomic<bool>& stopFlag) override {
for (long long i = area_of_responsibility[0]; i < area_of_responsibility[1] && !stopFlag; ++i) {
if (inputData[0][i] == targetNumber) {
found = true;
foundIndex = i;
stopFlag = true;
if (verbose) {
std::lock_guard<std::mutex> lock(outputMutex);
std::cout << "Thread found the number " << targetNumber << " at index " << i << std::endl;
}
break;
}
}
return {};
}
bool test_result(const std::vector<int*>& input_data, const std::vector<int*>&, long long dataSize) override {
if (foundIndex < 0 || foundIndex >= dataSize || input_data[0][foundIndex] != targetNumber) {
if (verbose) {
std::cerr << "Test failed. Target number " << targetNumber << " was not correctly found." << std::endl;
}
return false;
}
return true;
}
std::vector<int*> concat_results(const std::vector<std::vector<int*>>& partial_results, const std::vector<int*>& inputData, int, long long) override {
return inputData;
}
void cleanupData(std::vector<int*>& data, std::vector<std::vector<int*>>& result) const override {
if (!data.empty() && data[0] != nullptr) {
delete[] data[0];
data[0] = nullptr;
}
data.clear();
for (auto& res : result) {
if (!res.empty() && res[0] != nullptr) {
delete[] res[0];
res[0] = nullptr;
}
}
result.clear();
}
};
class LinearSearch : public SearchAlgorithms {
public:
LinearSearch(int threadCount, long long dataSize, bool verbose = false)
: SearchAlgorithms(threadCount, dataSize, verbose) {}
[[nodiscard]] std::string getType() const override {
return "LinearSearch";
}
protected:
std::vector<int*> execute(const std::vector<long long>& area_of_responsibility, const std::vector<int*>& inputData, std::atomic<bool>& stopFlag) override {
for (long long i = area_of_responsibility[0]; i < area_of_responsibility[1] && !stopFlag; ++i) {
if (inputData[0][i] == targetNumber) {
found = true;
foundIndex = i;
stopFlag = true;
if (verbose) {
std::lock_guard<std::mutex> lock(outputMutex);
std::cout << "Thread found the number " << targetNumber << " at index " << i << std::endl;
}
break;
}
}
return {};
}
};
class BinarySearch : public SearchAlgorithms {
public:
BinarySearch(int threadCount, long long dataSize, bool verbose = false)
: SearchAlgorithms(threadCount, dataSize, verbose) {}
[[nodiscard]] std::string getType() const override {
return "BinarySearch";
}
protected:
std::vector<int*> execute(const std::vector<long long>& area_of_responsibility, const std::vector<int*>& inputData, std::atomic<bool>& stopFlag) override {
long long start = area_of_responsibility[0];
long long end = area_of_responsibility[1];
while (start < end && !stopFlag) {
long long mid = start + (end - start) / 2;
if (inputData[0][mid] == targetNumber) {
found = true;
foundIndex = mid;
stopFlag = true;
if (verbose) {
std::lock_guard<std::mutex> lock(outputMutex);
std::cout << "Thread found the number " << targetNumber << " at index " << mid << std::endl;
}
break;
} else if (inputData[0][mid] < targetNumber) {
start = mid + 1;
} else {
end = mid;
}
}
return {};
}
std::vector<int*> generateData(long long dataSize) override {
auto data = SearchAlgorithms::generateData(dataSize);
std::sort(data[0], data[0] + dataSize); // Ensure data is sorted for binary search
return data;
}
};