// This is a function that returns the index // indicating the location of a value in the // array A. This version terminates early if // the value is found. // // Precondition: A is sorted in ascending order // and contains N elements // Postcondition: If the value is in A, its index // is returned. If the value is not found, a // -1 is returned instead. int BinSearch1 (int A[], int N, int value) { int min, max, mid; min = 0; max = N - 1; while (min <= max) { mid = (min + max)/2; if (A[mid] == value) return mid; if (value < A[mid]) max = mid - 1; else min = mid + 1; } return -1; } // This is a function that returns the index // indicating the location of a value in the // array, A. It does not terminate early if the // value is found - this saves one comparison each // iteration, and is actually more efficient on average // compared to the early termination version. // Precondition: A is sorted in ascending order // and contains N elements. // Postcondition: If the value is in A, found is 'true' // and the index of the element is returned in index. If // the value is not in A, found is 'false' and index contains // the location where value should be, relative to the other // elements in A void BinSearch2 (int A[], int N, int value, int& index, int& found) { int min, max, mid; min = 0; max = N - 1; while (min <= max) { mid = (min + max)/2; if (value < A[mid]) max = mid - 1; else min = mid + 1; } index = mid; found = (A[index] == value); }