#include #include #include #include #include using namespace std; const MaxListSize = 1000; int main() { int List[MaxListSize]; int ListSize = 0; // extract the list ifstream myin("sorted.dat"); if (!myin) { cerr << "Cannot open input file" << endl; return 1; } for (int i = 0; (i < MaxListSize) && (myin >> List[i]); ++i) { ++ListSize; } // get the key cout << "Enter key value: "; int key; cin >> key; cout << endl; // perform the binary search int comparisons = 0; // number of comparisons so far int left = 0; int right = ListSize - 1; int spot = ListSize; // spot is where the value can be found, we are // guessing its not there while (left <= right) { int p = (left + right) / 2; cout << "Index range: " << setw(4) << left << " .. " << setw(4) << p << " .. " << setw(4) << right << " has value range: " << setw(4) << List[left] << " .. " << setw(4) << List[p] << setw(4) << " .. " << setw(4) << List[right] << endl; // determine which half of the range the key is in if (key == List[p]) { // found it ++comparisons; spot = p; break; } else if (key < List[p]) { // key cannot be in right half ++comparisons; // one for the if test ++comparisons; // one for the else if test right = p - 1; } else { // key cannot be in left half ++comparisons; // one for the if test ++comparisons; // one for the else if test (which brought us here) left = p + 1; } } // display search results cout << endl; if ((spot < ListSize) && (List[spot] == key)) { cout << "Found " << key << ".\n" << endl << "Number of comparisons required: " << comparisons << " to process list of size " << ListSize << endl; } else { cout << "Did not find " << key << ".\n" << endl << "Number of comparisons required: " << comparisons << " to process list of size " << ListSize << endl; } // we are all done getch(); return 0; }