02/21/00
COM1100 Winter2000 Yuhong Yin
10
Binary search algorithm – con’d
nwhile (left <= right) {
n middle = (left + right) / 2; // find the middle element
n    // compare the desired element with the middle
n     if (key == list[middle]) { // if equal, return the position of the middle
n        return middle;
n    }
n    else if (key > list[middle]) { // if desired element is greater than the middle
n        left = middle + 1; // change the left pointer
n    }
n   else { // if desired element is less than the middle
n        right = middle -1; // change the right pointer
n    }
n}
nreturn -1; // if none of the element matches, return -1
n}
n