I wrote a program which it should be able to do perform a binary search from 1-1000, the question gave by the teacher wants us to do it without array such as int array[] = {1, 2, 3, 4, 5....};
, instead, he wants us to do it like let the user pick a number then use binary search. ps. I am new to c++ and I am still learning procedure programming.
#include <iostream>
//binary search
using namespace std;
//set function for binary search, high = highest range, low = lowest range, x = the number given by the user.
int binarySearch(int x) {
int high = 1000, low = 1;
int search = (high + low) / 2; //set search as the equation of the search
//search = 500
if (search == x)
return search;
while (search != x) {
if(x > search) {
search = (search + high) / 2;
} else if (x < search) {
search = (search + low) / 2;
}
cout << search << endl;
}
return search;
}
int main()
{
int x;
cout << "Enter a number to search: (1-1000) ";
cin >> x;
cout << binarySearch(x);
return 0;
}
For example, if you enter 150, the outcome will continuously give the outcome of 571, 286, 143, 571, 286 until you ask it to stop. Different inputs will have different outcomes, but they will keep giving 3 or 4 the same number and keep looping it.