-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSorting Algorithms.cpp
More file actions
977 lines (822 loc) · 30.4 KB
/
Copy pathSorting Algorithms.cpp
File metadata and controls
977 lines (822 loc) · 30.4 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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
/*
* Authors:
* Author1: Esraa Emary Abd El-Salam ID: 20230054
* Author2: Mohammed Atef Abd El-Kader ID: 20231143
* Author3: Mariam Badr Yehia ID: 20230391
* Author4: John Ayman Demian ID: 20230109
* Author5: George Malak Magdy ID: 20231042
* Description: The Sorting System is designed to help sort dynamically allocated data using nine different sorting algorithms.
It provides an interactive menu for selecting a sorting method, supports various data types using templates,
and displays each sorting step for better understanding.
* Date: 23 / 3 / 2025
* Prof: Dr. Besheer
* Version: V7.0
*/
// < ========================================================================================== >
#include <bits/stdc++.h>
using namespace std;
// ----------------------------------------------- GLOBAL VARIABLES
bool isNegativeElement = false;
bool runFile = false;
int indexInFile = 0;
string *contentOfFile; // Array of the content of the file.
// ----------------------------------------------- HELPER FUNCTIONS
// check if input is integer.
bool isValidInteger(const string &str) {
static const regex integerPattern(R"(^-?\d+$)");
return regex_match(str, integerPattern);
}
// check if input is double or float.
bool isValidFloat(const string &str) {
static const regex floatPattern(R"(^-?\d+(\.\d+)?$)");
return regex_match(str, floatPattern);
}
// ----------------------------------------------- CLASS DEFINITION
template<typename T>
class SortingSystem {
T *data;
int size;
void inputData();
void display(T arr[], int arrSize);
void countSortForRadix(int exp);
void mergeSortHelper();
void quickSortHelper();
public:
SortingSystem(int n);
~SortingSystem();
void insertionSort();
void selectionSort();
void bubbleSort();
void shellSort();
void mergeSort(int left, int right);
void quickSort(int first, int last);
void countSort();
void radixSort();
void bucketSort();
void merge(int left, int mid, int right);
int partition(int low, int high);
void displayData();
void measureSortTime(void (SortingSystem<T>::*sortFunc)());
void showMenu();
};
// ----------------------------------------------- CLASS IMPLEMENTATION
// --------------------- CONSTRUCTOR & INPUT DATA & DESTRUCTOR
template<typename T>
SortingSystem<T>::SortingSystem(const int n) : size(n) {
this->data = new T[size];
inputData();
}
template<typename T>
void SortingSystem<T>::inputData() {
if (runFile) {
for (int i = 1; i <= this->size; ++i) {
// Handle if the type of data is strings.
if constexpr (is_same<T, string>::value) {
this->data[i - 1] = contentOfFile[indexInFile++];
cout << "Element " << i << " : " << this->data[i - 1] << endl;
}
// Handle if the type of data is char.
else if constexpr (is_same<T, char>::value) {
this->data[i - 1] = contentOfFile[indexInFile++][0];
cout << "Element " << i << " : " << this->data[i - 1] << endl;
}
// Handle if the type of data is float and double.
else if constexpr (is_same<T, double>::value || is_same<T, float>::value) {
string element;
while (true) {
element = contentOfFile[indexInFile++];
if (isValidFloat(element)) {
this->data[i - 1] = stod(element);
cout << "Element " << i << " : " << this->data[i - 1] << endl;
break;
}
cout << "Invalid Input!\n\n";
}
}
// Handle if the type of data is int and long.
else {
string element;
while (true) {
element = contentOfFile[indexInFile++];
if (isValidInteger(element)) {
this->data[i - 1] = stoll(element);
if (this->data[i - 1] < 0) isNegativeElement = true;
cout << "Element " << i << " : " << this->data[i - 1] << endl;
break;
}
cout << "Invalid Input!\n\n";
}
}
}
} else {
for (int i = 1; i <= this->size; ++i) {
cout << "Please, enter element " << i << " :";
string element;
// Get the input and check if it is empty.
getline(cin, element);
while (element.empty()) {
getline(cin, element);
cout << "Invalid Input!\n";
cout << "\nPlease, enter element " << i << " :";
}
// Handle if the type of data is strings.
if constexpr (is_same<T, string>::value) {
this->data[i - 1] = element;
}
// Handle if the type of data is char.
else if constexpr (is_same<T, char>::value) {
this->data[i - 1] = element[0];
}
// Handle if the type of data is float and double.
else if constexpr (is_same<T, double>::value || is_same<T, float>::value) {
while (true) {
if (isValidFloat(element)) {
this->data[i - 1] = stod(element);
break;
}
cout << "Invalid Input!\n";
cout << "\nPlease, enter element " << i << " :";
getline(cin, element);
}
}
// Handle if the type of data is int and long.
else {
while (true) {
if (isValidInteger(element)) {
this->data[i - 1] = stoll(element);
if (this->data[i - 1] < 0) isNegativeElement = true;
break;
}
cout << "Invalid Input!\n";
cout << "\nPlease,enter element " << i << " :";
getline(cin, element);
}
}
}
}
cout << endl;
}
template<typename T>
SortingSystem<T>::~SortingSystem() {
delete[] this->data;
}
// --------------------- INSERTION SORT
template<typename T>
void SortingSystem<T>::insertionSort() {
cout << "Sorting using Insertion Sort...\n\n";
cout << "Initial Data: ";
displayData();
for (int i = 1, j; i < this->size; i++) {
T temp = this->data[i]; // put element in temp to compare with elements before it.
for (j = i; j > 0 && temp < this->data[j - 1]; j--)
this->data[j] = this->data[j - 1];
this->data[j] = temp;
// Display each iteration in sorting.
if (i < this->size - 1) {
cout << "Iteration " << i << " : ";
displayData();
}
}
// Display the final sorted data.
cout << endl << "Sorted Data: ";
displayData();
}
// Another version to bucket sort
template<typename T>
void insertionSortForBucket(T buck[], int size) {
for (int i = 1, j; i < size; i++) {
T temp = buck[i];
for (j = i; j > 0 && temp < buck[j - 1]; j--)
buck[j] = buck[j - 1];
buck[j] = temp;
}
}
// --------------------- SELECTION SORT
template<typename T>
void SortingSystem<T>::selectionSort() {
cout << "Sorting using Selection Sort...\n\n";
cout << "Initial Data: ";
displayData();
for (int i = 0; i < (this->size - 1); ++i) {
int minIndex = i;
for (int j = (i + 1); j < this->size; ++j) {
if (this->data[j] < this->data[minIndex]) {
minIndex = j;
}
}
swap(this->data[i], this->data[minIndex]);
// Display each Iteration in sorting
cout << "Iteration " << i + 1 << " : ";
displayData();
}
// Display the final sorted data.
cout << endl << "Sorted Data: ";
displayData();
}
// --------------------- BUBBLE SORT
template<typename T>
void SortingSystem<T>::bubbleSort() {
cout << "Sorting using Bubble Sort...\n\n";
cout << "Initial Data: ";
displayData();
long long num_iteration = 1;
for (int i = 0; i < this->size; i++) {
for (int j = this->size - 1; j > i; --j) {
if (this->data[j - 1] > this->data[j]) {
swap(this->data[j - 1], this->data[j]);
// Display each Iteration in sorting
cout << "Iteration " << num_iteration << " : ";
displayData();
num_iteration++;
}
}
}
// Display the final sorted data.
cout << endl << "Sorted Data: ";
displayData();
}
// --------------------- SHELL SORT
template<typename T>
void SortingSystem<T>::shellSort() {
cout << "Sorting using Sell Sort...\n\n";
cout << "Initial Data: ";
displayData();
long long num_iteration = 1;
for (int gap = this->size / 2; gap > 0; gap /= 2) {
for (int i = gap; i < this->size; i += 1) {
T temp = this->data[i];
int j;
for (j = i; j >= gap && data[j - gap] > temp; j -= gap)
this->data[j] = this->data[j - gap];
this->data[j] = temp;
}
// Display each Iteration in sorting
cout << "Iteration " << num_iteration << " : ";
displayData();
num_iteration++;
}
// Display the final sorted data.
cout << endl << "Sorted Data: ";
displayData();
}
// --------------------- MERGE SORT
int iteration = 0;
template<typename T>
void SortingSystem<T>::merge(const int left, const int mid, const int right) {
const int n1 = mid - left + 1;
const int n2 = right - mid;
T *left_data = new T[n1];
T *right_data = new T[n2];
for (int i = 0; i < n1; i++)
left_data[i] = this->data[left + i];
for (int i = 0; i < n2; i++)
right_data[i] = this->data[mid + 1 + i];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (left_data[i] <= right_data[j]) {
this->data[k] = left_data[i];
i++;
} else {
this->data[k] = right_data[j];
j++;
}
k++;
}
while (i < n1) {
this->data[k] = left_data[i];
i++;
k++;
}
while (j < n2) {
this->data[k] = right_data[j];
j++;
k++;
}
// Print the current state of the data after iteration of merge sort
iteration++;
cout << "Iteration " << iteration << " : ";
displayData();
// Free temporary data arrays
delete[] left_data;
delete[] right_data;
}
template<typename T>
void SortingSystem<T>::mergeSort(const int left, const int right) {
if (left < right) {
const int mid = left + (right - left) / 2;
mergeSort(left, mid); // Sort left half
mergeSort(mid + 1, right); // Sort right half
merge(left, mid, right); // Merge the two halves
}
}
template<typename T>
void SortingSystem<T>::mergeSortHelper() {
cout << "Sorting using Merge Sort...\n\n";
cout << "Initial Data: ";
displayData();
mergeSort(0, this->size - 1);
// Display each Iteration in sorting
cout << endl << "Sorted Data: ";
displayData();
}
// --------------------- Quick SORT
template<typename T>
int SortingSystem<T>::partition(int low, const int high) {
swap(this->data[low], this->data[(low + high) / 2]);
T pivot = this->data[low];
int smallIndex = low;
for (int index = low + 1; index <= high; index++) {
if (this->data[index] < pivot) {
smallIndex++;
swap(this->data[smallIndex], this->data[index]);
}
}
swap(data[low], data[smallIndex]);
// Print the current partition
cout << "Pivot: " << pivot << " --> [";
for (int i = low; i < smallIndex; i++) {
cout << this->data[i];
if (i < smallIndex - 1) cout << ", ";
}
cout << "] " << pivot << " [";
for (int i = smallIndex + 1; i <= high; i++) {
cout << this->data[i];
if (i < high) cout << ", ";
}
cout << "]" << endl;
return smallIndex;
}
template<typename T>
void SortingSystem<T>::quickSort(const int first, const int last) {
if (first < last) {
int pivotLocation = partition(first, last);
quickSort(first, pivotLocation - 1);
quickSort(pivotLocation + 1, last);
}
}
template<typename T>
void SortingSystem<T>::quickSortHelper() {
cout << "Sorting using Quick Sort...\n\n";
cout << "Initial Data: ";
displayData();
quickSort(0, this->size - 1);
// Display each Iteration in sorting
cout << endl << "Sorted Data: ";
displayData();
}
// --------------------- COUNT SORT
template<typename T>
void SortingSystem<T>::countSort() {
cout << "Sorting using Count Sort...\n\n";
cout << "Initial Data: ";
displayData();
// Find the maximum value in the array
int Max_Value = this->data[0];
for (int i = 1; i < this->size; i++) {
Max_Value = max(Max_Value, this->data[i]);
}
// Create and initialize a count array
int *C = new int[Max_Value + 1](); // Dynamic allocation, initialized to 0
cout << "Max_Value: " << Max_Value << endl;
// Step 1: Count occurrences
for (int i = 0; i < this->size; i++) {
C[this->data[i]]++;
}
// Step 2: Compute cumulative count
cout << "Cumulative Data: [";
for (int i = 1; i <= Max_Value; i++) {
C[i] += C[i - 1];
if (i != Max_Value) cout << C[i] << ", ";
else cout << C[i];
}
cout << "]" << endl;
T *B = new T[this->size]; // Create the output array
// Step 3: Place elements in sorted order
for (int i = this->size - 1; i >= 0; i--) {
B[C[this->data[i]] - 1] = this->data[i];
C[this->data[i]]--;
}
// Step 4: Copy sorted array back to data
for (int i = 0; i < this->size; i++) {
this->data[i] = B[i];
}
cout << endl << "Sorted Data: ";
displayData();
// Free the temporary data array.
delete[] C;
delete[] B;
}
// --------------------- RADIX SORT
template<typename T>
void SortingSystem<T>::countSortForRadix(int exp) {
T *B = new T[this->size]; // Output array
int C[10] = {0}; // Counting array for digits (0-9)
// Step 1: Count occurrences of each digit at place 'exp'
for (int i = 0; i < this->size; i++) {
int digit = (this->data[i] / exp) % 10;
C[digit]++;
}
// Step 2: Compute cumulative count
for (int i = 1; i < 10; i++) {
C[i] += C[i - 1];
}
// Step 3: Place elements in sorted order (stable sort)
for (int i = this->size - 1; i >= 0; i--) {
int digit = (this->data[i] / exp) % 10;
B[C[digit] - 1] = this->data[i];
C[digit]--;
}
// Step 4: Copy sorted elements back to an original array
for (int i = 0; i < this->size; i++) {
this->data[i] = B[i];
}
// Free dynamically allocated memory
delete[] B;
}
template<typename T>
void SortingSystem<T>::radixSort() {
cout << "Sorting using Radix Sort...\n\n";
cout << "Initial Data: ";
displayData();
int Max_Value = this->data[0];
for (int i = 1; i < this->size; i++) {
Max_Value = max(Max_Value, this->data[i]);
}
// Apply counting sort for each digit place
for (int exp = 1; Max_Value / exp > 0; exp *= 10) {
countSortForRadix(exp);
cout << "After sorting on place value " << exp << ": ";
displayData();
}
cout << endl << "Sorted Data: ";
displayData();
}
// --------------------- BUCKET SORT
template<typename T>
void SortingSystem<T>::bucketSort() {
cout << "Sorting using Bucket Sort...\n\n";
cout << "Initial Data: ";
displayData();
T minimum = (this->data[0]), maximum = (this->data[0]);
for (int i = 0; i < this->size; ++i) {
T val = (this->data[i]);
if (val > maximum) maximum = val;
if (val < minimum) minimum = val;
}
// 2D arrays store buckets, each bucket has a specific range of values.
T **buckets = new T *[this->size];
// array follow indexes for each bucket.
int *bucket_sizes = new int[this->size];
// initialize the buckets and their indexes.
for (int i = 0; i < this->size; ++i) {
buckets[i] = new T[this->size];
bucket_sizes[i] = 0;
}
if (minimum == maximum) {
cout << endl << "Sorted Data: ";
displayData();
return;
}
for (int i = 0; i < this->size; ++i) {
// Calculate the Normalization that uses to determine the index and the bucket which has the value.
T norm = (this->data[i] - minimum) / (maximum - minimum);
// Calculate the index by Normalization.
int index = static_cast<int>(norm * (this->size - 1));
// store the value in its bucket
buckets[index][bucket_sizes[index]] = this->data[i];
bucket_sizes[index]++;
}
// Sort each bucket's value by insertion sort.
int index = 1;
for (int i = 0; i < this->size; ++i) {
if (bucket_sizes[i] > 0) {
insertionSortForBucket(buckets[i], bucket_sizes[i]);
cout << "Iteration " << index++ << ": ";
display(buckets[i], bucket_sizes[i]);
}
}
// Return again the values in original Array
index = 0;
for (int i = 0; i < this->size; ++i) {
for (int j = 0; j < bucket_sizes[i]; ++j) {
data[index++] = buckets[i][j];
}
}
cout << endl << "Sorted Data: ";
displayData();
// Free the temporary data array.
for (int i = 0; i < this->size; ++i) {
delete[] buckets[i];
}
delete[] buckets;
delete[] bucket_sizes;
}
// --------------------- DISPLAY DATA
template<typename T>
void SortingSystem<T>::display(T arr[], int arrSize) {
cout << "[";
for (int i = 0; i < arrSize; ++i) {
if (i != arrSize - 1) cout << arr[i] << ", ";
else cout << arr[i];
}
cout << "]" << endl;
}
template<typename T>
void SortingSystem<T>::displayData() {
cout << "[";
for (int i = 0; i < this->size; ++i) {
if (i != this->size - 1) cout << this->data[i] << ", ";
else cout << this->data[i];
}
cout << "]" << endl;
}
// --------------------- MEASURE SORT TIME
template<typename T>
void SortingSystem<T>::measureSortTime(void(SortingSystem<T>::*sortFunc)()) {
using Clock = chrono::high_resolution_clock;
auto startTime = Clock::now(); // Start Time Point.
(this->*sortFunc)(); // Call the function without parameters
auto endTime = Clock::now(); // End Time Point.
chrono::duration<double> duration = endTime - startTime;
cout << "Sorting time: " << duration.count() << " seconds." << endl << endl;
}
// --------------------- SHOW MENU
template<typename T>
void SortingSystem<T>::showMenu() {
while (true) {
cout << "Select a sorting algorithm:" << endl;
cout << "1. Insertion Sort." << endl;
cout << "2. Selection Sort." << endl;
cout << "3. Bubble Sort." << endl;
cout << "4. Shell Sort." << endl;
cout << "5. Merge Sort." << endl;
cout << "6. Quick Sort." << endl;
cout << "7. Count Sort (only for integers)." << endl;
cout << "8. Radix Sort (only for integers)." << endl;
cout << "9. Bucket Sort (only for integers and floating point numbers)." << endl;
cout << "0. Exit From Menu." << endl;
string choice;
if (runFile) {
choice = contentOfFile[indexInFile++];
cout << "Your choice (0 - 9) : " << choice << endl;
} else {
cout << "Enter your choice (0 - 9):";
getline(cin, choice);
if (choice != "1" && choice != "2" && choice != "3" && choice != "4" && choice != "5" && choice != "6" &&
choice != "7" && choice != "8" && choice != "9" && choice != "0") {
cout << "Invalid choice. Please try again." << endl << endl;
continue;
}
}
// Create a temporary data array to store the original data before sorting it.
T *tempData = new T[this->size];
for (int i = 0; i < this->size; i++) {
tempData[i] = this->data[i];
}
if (choice == "1")
measureSortTime(&SortingSystem::insertionSort);
else if (choice == "2")
measureSortTime(&SortingSystem::selectionSort);
else if (choice == "3")
measureSortTime(&SortingSystem::bubbleSort);
else if (choice == "4")
measureSortTime(&SortingSystem::shellSort);
else if (choice == "5") {
measureSortTime(&SortingSystem::mergeSortHelper);
iteration = 0;
}
else if (choice == "6")
measureSortTime(&SortingSystem::quickSortHelper);
else if (choice == "7") {
if (!isNegativeElement) {
if constexpr (is_integral<T>::value && !is_same<T, char>::value && !is_same<T, wchar_t>::value &&
!is_same<T, char16_t>::value && !is_same<T, char32_t>::value) {
measureSortTime(&SortingSystem::countSort);
}
else cout << "Count Sort is only available for integers." << endl << endl;
}
else cout << "Count Sort is only available for integers." << endl << endl;
}
else if (choice == "8") {
if (!isNegativeElement) {
if constexpr (is_integral<T>::value && !is_same<T, char>::value && !is_same<T, wchar_t>::value &&
!is_same<T, char16_t>::value && !is_same<T, char32_t>::value) {
measureSortTime(&SortingSystem::radixSort);
}
else cout << "Radix Sort is only available for integers." << endl << endl;
}
else cout << "Radix Sort is only available for integers." << endl << endl;
}
else if (choice == "9") {
if constexpr (is_integral<T>::value || is_floating_point<T>::value) {
measureSortTime(&SortingSystem::bucketSort);
}
else cout << "Bucket Sort is only available for integers and floating point numbers." << endl << endl;
}
else if (choice == "0") {
delete[] tempData;
return;
}
// Free the temporary data array and restore the original data.
delete[] this->data;
this->data = tempData;
}
}
// ----------------------------------------------- ANOTHER SOME HELPER FUNCTIONS
void runFromTerminal() {
while (true) {
// Choose the data type for the sorting system (numbers or strings).
isNegativeElement = false;
string dataType;
while (true) {
cout << "\nPlease, enter the data type" << endl;
cout << "1) Integers." << endl;
cout << "2) Doubles & Floats." << endl;
cout << "3) Strings." << endl;
cout << "4) Characters." << endl;
cout << "Please, enter your choice:";
getline(cin, dataType);
if (dataType == "1" || dataType == "2" || dataType == "3" || dataType == "4") break;
cout << "Invalid choice. Please enter a valid number." << endl << endl;
}
// Enter the number of elements to be sorted in the system.
string numberOfElements;
while (true) {
cout << "\nPlease, enter the number of elements:";
getline(cin, numberOfElements);
if (isValidInteger(numberOfElements) && stoi(numberOfElements) > 0) break;
cout << "Invalid input. Please enter a valid number." << endl << endl;
}
// Create the sorting system object based on the data type.
if (dataType == "1") {
SortingSystem<int> sortingSystem(stoi(numberOfElements));
sortingSystem.showMenu();
} else if (dataType == "2") {
SortingSystem<double> sortingSystem(stoi(numberOfElements));
sortingSystem.showMenu();
} else if (dataType == "3") {
SortingSystem<string> sortingSystem(stoi(numberOfElements));
sortingSystem.showMenu();
} else if (dataType == "4") {
SortingSystem<char> sortingSystem(stoi(numberOfElements));
sortingSystem.showMenu();
}
// Ask the user if they want to continue using the system or exit.
string choice;
while (true) {
cout << "\nDo you want to continue? (y/n):";
getline(cin, choice);
choice = (choice);
if (choice == "Y" || choice == "y" || choice == "N" || choice == "n") break;
else cout << "Invalid choice. Please try again." << endl << endl;
}
if (choice == "N" || choice == "n") break;
}
}
void runFromFile() {
string fileContent, fileName, element;
stringstream content;
cout << "\nPlease, enter file name:";
while (true) {
// Get the file name and check the validity of format.
getline(cin, fileName);
if (fileName.size() < 5) {
cout << "\nThe file name should be like this ----> (file name).txt\n";
cout << "Please, enter a valid file name:";
continue;
}
// Check file extension.
if (fileName.substr(fileName.size() - 4, 4) != ".txt") {
cout << "\nThe file name should be like this ----> (file name).txt\n";
cout << "Please, enter a valid file name:";
continue;
}
// Check if the file exists.
ifstream file(fileName);
if (!file.good()) {
cout << "\nThe file name should be like this ----> (file name).txt\n";
cout << "Please, enter a valid file name:";
continue;
}
content << file.rdbuf();
break;
}
fileContent = content.str();
// Put the content of the file into an array.
int count = 0;
for (char character: fileContent) {
if ((character == '\n' || character == ' ') && !element.empty()) {
count++;
element = "";
}
else if (character == '\n' || character == ' ') {
continue;
}
else element += character;
}
// Reset global variables.
delete [] contentOfFile;
contentOfFile = new string[count + 1];
indexInFile = 0;
count = 0;
element = "";
for (char character: fileContent) {
if ((character == '\n' || character == ' ') && !element.empty()) {
contentOfFile[count++] = element;
element = "";
}
else if (character == '\n' || character == ' ') {
continue;
}
else element += character;
}
contentOfFile[count] = element;
while (true) {
isNegativeElement = false;
string dataType;
while (true) {
cout << "\nPlease, enter the data type" << endl;
cout << "1) Integers." << endl;
cout << "2) Doubles & Floats." << endl;
cout << "3) Strings." << endl;
cout << "4) Characters." << endl;
cout << "Please, enter your choice:";
dataType = contentOfFile[indexInFile++];
cout << "Your choice :" << dataType << endl << endl;
if (dataType == "1" || dataType == "2" || dataType == "3" || dataType == "4") break;
cout << "Invalid choice. Please enter a valid number." << endl << endl;
}
string numberOfElements;
while (true) {
numberOfElements = contentOfFile[indexInFile++];
cout << "Number of elements:" << numberOfElements << endl << endl;
if (isValidInteger(numberOfElements) && stoi(numberOfElements) > 0) break;
cout << "Invalid input. Please enter a valid number." << endl << endl;
}
// Create the sorting system object based on the data type.
if (dataType == "1") {
SortingSystem<int> sortingSystem(stoi(numberOfElements));
sortingSystem.showMenu();
} else if (dataType == "2") {
SortingSystem<double> sortingSystem(stoi(numberOfElements));
sortingSystem.showMenu();
} else if (dataType == "3") {
SortingSystem<string> sortingSystem(stoi(numberOfElements));
sortingSystem.showMenu();
} else if (dataType == "4") {
SortingSystem<char> sortingSystem(stoi(numberOfElements));
sortingSystem.showMenu();
}
// check if user wants to exit.
string choice = contentOfFile[indexInFile++];
while (true) {
cout << "Do you want to continue? (y/n):" << choice << endl;
if (choice == "Y" || choice == "y" || choice == "N" || choice == "n") break;
else cout << "Invalid choice. Please try again." << endl << endl;
choice = contentOfFile[indexInFile++];
}
if (choice == "N" || choice == "n") break;
}
}
// ----------------------------------------------- MAIN FUNCTION
int main() {
cout << "\n------------- WELCOME TO OUR SORTING SYSTEM -------------\n";
string choice;
contentOfFile = new string[1];
while (true) {
// Reset global variables.
runFile = false;
while (true) {
cout << "\nWhat do you want to do?" << endl;
cout << "1) Sorting System." << endl;
cout << "2) Exit." << endl;
cout << "Please, enter your choice:";
getline(cin, choice);
// Check the validity of input.
if (choice == "1" || choice == "2") break;
cout << "Invalid choice. Please, Try again." << endl << endl;
}
// Exit the system.
if (choice == "2") break;
while (true) {
cout << "\nWhat do you want to do?" << endl;
cout << "1) Run From Terminal." << endl;
cout << "2) Run From File." << endl;
cout << "3) Exit." << endl;
cout << "Please, enter your choice:";
getline(cin, choice);
// Check the validity of input.
if (choice == "1" || choice == "2" || choice == "3") break;
cout << "Invalid choice. Please, Try again." << endl << endl;
}
// Run from the terminal.
if (choice == "1") runFromTerminal();
// Run from the file.
else if (choice == "2") {
runFile = true;
runFromFile();
} else continue;
}
delete [] contentOfFile;
cout << "\n----- Thank you for using our system! Goodbye! -----" << endl;
}