int BinarySearch(const apvector & list, int target) // This function uses a Binary Search to search an array // ('list') of integers for a specific element ('target'). // Once found, the index of the element is returned. // If 'target' is not found, -1 is returned. // Remember that the first element in an array is // in position 0, not position 1. // NOTE: For the binary search to work properly, the // list MUST already be sorted. { int left=0, right=list.length()-1, middle; int place = -1; while (left <= right) { middle = (left + right) / 2; // Find index of middle element // between 'left' and 'right' if (target > list[middle]) left = middle + 1; else if (target < list[middle]) right = middle - 1; else return middle; // 'target' must be equal to list[middle] } return place; }