// Faan Tone Liu , demo program for comp 1672, winter 2003 // recursive Binary search function and insert sort function, and testing it #include #include using namespace std; int binarySearchrec(const int b[], int searchkey, int low, int high); void insert_sort(int a[], int len); // read elements of an array in from a file. Sort them. // Get search key from user, search for it in array. int main() { const int maxarrlen(100); const int maxnamelen(80); char filename[maxnamelen]; ifstream listfile; int arr[maxarrlen]; int numelements(0); int key, result; cout << "Enter file name containing list (no more than 100 elements): "; cin >> filename; listfile.open(filename, ios::in); // open input file if (!listfile.is_open()) { cout << "Unable to open file." << endl; return 1; } // read the list from the file into the array while (listfile >> arr[numelements]) numelements = numelements + 1; //sort it insert_sort(arr, numelements); cout << "What number are you looking for? "; cin >> key; result = binarySearchrec(arr, key, 0, numelements-1); if (result < 0) cout << "The number was not found in the list" << endl; else cout << "The number " << key << " was found at position " << result << " of the array." << endl; return 0; } // sort the array a in increasing order // use an insert sort algorithm. This is an inefficient algorithm! // You should use merge sort or quick sort instead void insert_sort(int a[], int len) { int BadOrder, temp, location; // Traverse the list - checking for correct ordering for (BadOrder = 1; BadOrder < len; BadOrder++) { if (a[BadOrder] < a[BadOrder-1]) { // this one's in the wrong place! temp = a[BadOrder]; // remember what this element is location = BadOrder; // these next few lines slides elements do { // down to make room for this one a[location] = a[location-1]; location--; } while (location>0 && a[location-1] > temp); a[location] = temp; // Put out-of-order number in the right place } } } //Search through array b which contains size elements to locate the // index of searchkey, a value we hope to find in b. If it is // not found, return -1 // Recursive version of binary search. int binarySearchrec(const int b[], int searchkey, int low, int high) { int middle((low+high)/2); if (low > high) return -1; if (b[middle] == searchkey) return middle; else if (b[middle] > searchkey) high = middle -1; else low = middle + 1; return binarySearchrec(b, searchkey, low, high); }