// // Program name: binsearch // Author: B. Massingill // // Purpose: // binsearch function implements binary search algorithm for // searching for an element of an array // main program tests function // #include #include #include // code for binary search function is in binsearch.h #include "binsearch.h" // code for sort function is in selectionSort.h #include "selectionSort.h" // ---- function prototypes (see below for comments) ---- int readFileIntoArray(const char fileName[], int a[], const int arrayLength); void displayArray(const int a[], const int n); void searchArray(const int a[], const int n); // ---- main program ---- int main(int argc, char *argv[]) { const int MaxArrayLength = 100; int a[MaxArrayLength]; int arrayLength; char prompt[] = "Enter D to display array, " "S to search, " "Q to quit:\n"; char cmd; if (argc < 2) { cerr << "Must supply filename as command-line argument" << endl; exit(1); } arrayLength = readFileIntoArray(argv[1], a, MaxArrayLength); selectionSort(a, arrayLength); cout << prompt; while ((cin >> cmd) && (cmd != 'Q')) { if (cmd == 'D') displayArray(a, arrayLength); else if (cmd == 'S') searchArray(a, arrayLength); else cerr << "Invalid response\n"; cout << prompt; } return 0 ; } // ---- supporting functions ---- // precondition: // fileName is a null-terminated string representing a filename; // the file contains integers // arrayLength is the length of array a // postcondition: // if the file exists, up to arrayLength integers have been read // into a; the return value is the number of integers // read // otherwise an error message is printed and the program is // terminated int readFileIntoArray(const char fileName[], int a[], const int arrayLength) { ifstream inS; inS.open(fileName); if (inS.fail()) { cerr << "Unable to open file " << fileName << endl; exit(1); } int count = 0; while ((count < arrayLength) && (inS >> a[count])) count++; inS.close(); return count; } // precondition: // n is the size of a // postcondition: // a[0] .. a[n-1] have been printed void displayArray(const int a[], const int n) { cout << "Array elements:\n"; for (int i = 0; i < n; i++) cout << " " << a[i] << endl; return; } // precondition: // n is the size of a // postcondition: // user has prompted for a search value x // if x is found in a, its index is printed; otherwise a "not // found" message is printed void searchArray(const int a[], const int n) { int x; cout << "Enter element to search for:\n"; cin >> x; int index = binsearch(a, 0, n-1, x); if (index == -1) cout << "Not found\n"; else cout << "Found at position " << index << endl; return; }