-
Notifications
You must be signed in to change notification settings - Fork 0
/
Shorting game .cpp
89 lines (73 loc) · 1.96 KB
/
Shorting game .cpp
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
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
void merge(vector<int>& arr, int left, int middle, int right) {
int n1 = middle - left + 1;
int n2 = right - middle;
vector<int> leftArr(n1), rightArr(n2);
for (int i = 0; i < n1; ++i)
leftArr[i] = arr[left + i];
for (int j = 0; j < n2; ++j)
rightArr[j] = arr[middle + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k] = leftArr[i];
++i;
} else {
arr[k] = rightArr[j];
++j;
}
++k;
}
while (i < n1) {
arr[k] = leftArr[i];
++i;
++k;
}
while (j < n2) {
arr[k] = rightArr[j];
++j;
++k;
}
}
void mergeSort(vector<int>& arr, int left, int right) {
if (left < right) {
int middle = left + (right - left) / 2;
mergeSort(arr, left, middle);
mergeSort(arr, middle + 1, right);
merge(arr, left, middle, right);
}
}
void printArray(const vector<int>& arr) {
for (int num : arr)
cout << num << " ";
cout << endl;
}
vector<int> generateRandomArray(int size) {
vector<int> arr(size);
srand(time(0));
for (int i = 0; i < size; ++i) {
arr[i] = rand() % 100;
}
return arr;
}
void startGame() {
cout << "Welcome to the Divide and Conquer Sorting Game!" << endl;
int arraySize;
cout << "Enter the size of the array you want to sort: ";
cin >> arraySize;
vector<int> arr = generateRandomArray(arraySize);
cout << "Here is the unsorted array: ";
printArray(arr);
mergeSort(arr, 0, arr.size() - 1);
cout << "\nCongratulations! You've successfully sorted the array.\n";
cout << "Sorted array: ";
printArray(arr);
}
int main() {
startGame();
return 0;
}