// Faan Tone Liu , demo program for comp 1672, winter 2003 // Binary search function and insert sort function, and testing it #include #include using namespace std; int binarySearch(const int b[], int searchkey, int size); 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 = binarySearch(arr, key, numelements); 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; } //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 int binarySearch(const int b[], int searchkey, int size) { int low, middle, high; low = 0; high = size-1; while (low <= high) { middle = (low+high)/2; if (searchkey == b[middle]) // found it! return middle; else if (searchkey < b[middle]) // it's in the lower half high = middle -1; else low = middle + 1; } return -1; } // 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 } } }