#include #include using namespace std; int main() { const string a[] = { "Alabama", // 0 "Alaska", // 1 "Arizona", // 2 "Arkansas", // 3 "California", // 4 "Colorado", // 5 "Connecticut", // 6 "Delaware", // 7 "Florida", // 8 "Georgia", // 9 "Hawaii", //10 "Idaho", //11 "Illinois", //12 "Indiana", //13 "Iowa", //14 "Kansas", //15 "Kentucky", //16 "Louisiana", //17 "Maine", //18 "Maryland", //19 "Massachusetts", //20 "Michigan", //21 "Minnesota", //22 "Mississippi", //23 "Missouri", //24 "Montana", //25 "Nebraska", //26 "Nevada", //27 "New Hampshire", //28 "New Jersey", //29 "New Mexico", //30 "New York", //31 "North Carolina", //32 "North Dakota", //33 "Ohio", //34 "Oklahoma", //35 "Oregon", //36 "Pennsylvania", //37 "Rhode Island", //38 "South Carolina", //39 "South Dakota", //40 "Tennessee", //41 "Texas", //42 "Utah", //43 "Vermont", //44 "Virginia", //45 "Washington", //46 "West Virginia", //47 "Wisconsin", //48 "Wyoming" //49 }; const size_t n {size(a)}; //the number of elements in the array cout << "Please input the name of a state: "; string name; getline(cin, name); if (!cin) { cerr << "Sorry, couldn't input the name.\n"; return EXIT_FAILURE; } if (n == 0) { cerr << "Sorry, the array is empty.\n"; return EXIT_FAILURE; } //If the name is in the array, its subscript is //lo <= subscript <= hi //That means that if hi < lo, the name is not in the array. int lo {0}; int hi {n}; while (lo <= hi) { const int mid {(lo + hi) / 2}; //the average of lo and hi if (a[mid] == name) { cout << "Found \"" << name << "\" at subscript " << mid << ".\n"; return EXIT_SUCCESS; } else if (a[mid] < name) { lo = mid + 1; //Our guess was too low. } else { hi = mid - 1; //Our guess was too high. } } cout << "Sorry, \"" << name << "\" is not in the array.\n"; return EXIT_SUCCESS; }