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
|
#include <iostream>
using namespace std;
bool binarySearch(long array[], int, int accNumber);
int main()
{
long accounts[18] = {
1005231, 1250255, 1302850,3852085, 4520125, 4562555,
4581002, 5050552, 5552012,5658845, 6545231, 7576651,
7825877, 7881200, 7895122, 8080152, 8451277, 8777541 };
int accNumber, results;
cout << "\n\tPlease enter a valid Account Number: ";
cin >> accNumber;
results = binarySearch(accounts, 18, accNumber);
if (results == -1)
cout << "\n\tAccount number is invalid.";
else
cout << "\n\tAccount number " << accounts[results] << " is valid.\n";
return 0;
}
bool binarySearch(long array[], int SIZE, int accNumber)
{
int first = 0;
int last = 18 - 1;
int position = -1;
int middle;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == accNumber)
{
found = true;
position = middle;
}
else if (array[middle] > accNumber)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
|