For some reason, only 8777541, 4562555, and 3852085 are considered valid numbers. All of the other numbers are consider invalid or cause some kind of weird error.Code:#include <iostream> using namespace std; int search(long array[], int size, long value); int main() { long nums[] = {5658845, 8080152, 1005231, 4520125, 4562555, 6545231, 7895122, 5552012, 3852085, 8777541, 5050552, 7576651, 8451277, 7825877, 7881200, 1302850, 1250255, 4581002}; long number; int results; cout << "Enter a charge account number" << endl; cin >> number; while (results = search(nums, 18, number) == -1) { cin.clear(); cin.ignore(INT_MAX, '\n'); cout << "Invalid entry" << endl; cout << "Re-enter" << endl; cin >> number; } cout << "Your number is valid" << endl; return 0; } int search(long array[], int size, long value) { int first = 0; int middle; int last = size - 1; int position = -1; int found = 0; while (!found && first <= last) { middle = (first + last) / 2; if (array[middle] == value) { found = 1; position = middle; } else if (array[middle] > value) last = middle - 1; else first = middle = 1; } return position; }
Never mind. I realize that the numbers have to be sorted in order for a binary search to work.



LinkBack URL
About LinkBacks


