#include #include #include #include #include #include using namespace std; int main () { unsigned seed = chrono::system_clock::now().time_since_epoch().count(); default_random_engine engine {seed}; uniform_int_distribution distribution {0, 999}; auto r {bind(distribution, engine)}; //needed for RNG const size_t quantity {750}; int a[quantity]; //create the array for (int i {0}; i < quantity; ++i) { //populate the array a[i] = r(); } const size_t n {size(a)}; cout << "I have generated " << quantity << " random numbers between 0 and 1000.\n"; cout << "I will now generate a random target from those numbers to search for.\n"; const int target = a[r() % quantity]; //randomly select a generated number to search for cout << "Let's find " << target << " in the following array:\n\n"; for (int i {0}; i < n; ++i) { cout << setw(3) << a[i] << ", "; if (i % 15 == 14) { cout << "\n"; } } cout << "\nFirst, we need to sort the random numbers from low to high.\n\n"; for (int i {n}; i > 0; --i) { //bubble sort to get the array sorted lowest to highest for (int j = 0; j < i; ++j) { if (a[j] > a[j + 1]) { const int temp {a[j]}; a[j] = a[j + 1]; a[j + 1] = temp; } } } for (int i {0}; i < n; ++i) { cout << setw(3) << a[i] << ", "; if (i % 15 == 14) { cout << "\n"; } } cout << "\nNow that the array is organized from lowest to highest, we can use a binary search function to find " << target << ".\n"; int low {0}; int high {n}; while (low <= high) { //run the binary sort function, outputting the remaining possible options for the target number const int mid {(low + high) / 2}; if (a[mid] == target) { cout << "\nWe found " << target << "!!\n\n"; return EXIT_SUCCESS; } else if (a[mid] < target) { cout << "\nOur guess of " << a[mid] << " is too low.\nOur remaining options are:\n"; low = mid + 1; for (int i = low; i <= high; ++i) { cout << setw(3) << a[i] << ", "; } } else { cout << "\nOur guess of " << a[mid] << " is too high.\nOur remaining options are:\n"; high = mid - 1; for (int i = low; i <= high; ++i) { cout << setw(3) << a[i] << ", "; } } } cout << "Unfortunately, the target number could not be found.\n"; return EXIT_FAILURE; }