/* testsearch2.cpp CIS 150 David Klick 6/24/08 Demonstration of binary search. */ #include #include #include using std::cin; using std::cout; const int ARRAY_SIZE = 10; int bsearch(int n[], int len, int key); void sort_array(int n[], int len); void cont(); int main() { int nums[ARRAY_SIZE]; int i, val, pos; // randomize random number generator srand(time(NULL)); // fill array up with random ints (0-99) for (i=0; i key) hi = mid - 1; else if (n[mid] < key) lo = mid + 1; else return mid; } return -1; } /* void sort_array(int n[], int len); Arguments: int n[]: array of integers to be sorted int len: number of elements in array Returns: nothing (but a side effect is that the array passed in is put into ascending sorted order) Sorts the integer array n[] into ascending order. This is a very inefficient sort and should not be used for real-world problems. */ void sort_array(int n[], int len) { int i, j, tmp; for (i=0; i n[j]) { tmp = n[i]; n[i] = n[j]; n[j] = tmp; } } } } /* void cont(); Arguments: none Returns: nothing Clears input buffer and pauses waiting for user to press Enter. */ void cont() { if (cin.rdbuf()->sungetc() != -1 && cin.get() != '\n') cin.ignore(80,'\n'); cout << "Press enter to continue..."; cin.get(); } /* Sample output 13 15 27 33 36 50 51 54 89 90 1 not found 15 found at position 1 47 not found 95 not found 40 not found 60 not found 54 found at position 7 55 not found 78 not found 66 not found */