Referring back to the searching problem (see Exercise 1.1-3), observe that if the sequence A is sorted, we can check the midpoint of the sequence against v and eliminate half of the sequence from further consideration. Binary search is an algorithm that repeats this procedure, halving the size of the remaining portion of the sequence each time. Write pseudocode, either iterative or recursive, for binary search. Argue that the worst-case running time of binary search is (lg n).
/*
* Recursive version binary search.
*
* Search the given key in a n-elements sorted array A.
* Return the index if found, else return -1.
*/
int binarySearch1(int A[], int begin, int end, int key) {
if (begin >= end) {
return (A[begin] == key) ? begin : -1;
}
int middle = (begin + end) / 2;
if (A[middle] == key) {
return middle;
} else if (A[middle] > key) {
return binarySearch1(A, begin, middle - 1, key);
} else {
return binarySearch1(A, middle + 1, end, key);
}
}
/*
* Iterative version binary search.
*
* Search the given key in a n-elements sorted array A.
* Return the index if found, else return -1.
*/
int binarySearch2(int A[], int n, int key) {
int begin, end;
begin = 0;
end = n - 1;
while (begin <= end) {
int middle = (begin + end) / 2;
if (A[middle] == key) {
return middle;
} else if (A[middle] > key) {
end = middle -1;
} else {
begin = middle + 1;
}
}
return -1;
}
/*
* Recursive version binary search.
*
* Search the given key in a n-elements sorted array A.
* Return the index if found, else return -1.
*/
int binarySearch1(int A[], int begin, int end, int key) {
if (begin >= end) {
return (A[begin] == key) ? begin : -1;
}
int middle = (begin + end) / 2;
if (A[middle] == key) {
return middle;
} else if (A[middle] > key) {
return binarySearch1(A, begin, middle - 1, key);
} else {
return binarySearch1(A, middle + 1, end, key);
}
}
/*
* Iterative version binary search.
*
* Search the given key in a n-elements sorted array A.
* Return the index if found, else return -1.
*/
int binarySearch2(int A[], int n, int key) {
int begin, end;
begin = 0;
end = n - 1;
while (begin <= end) {
int middle = (begin + end) / 2;
if (A[middle] == key) {
return middle;
} else if (A[middle] > key) {
end = middle -1;
} else {
begin = middle + 1;
}
}
return -1;
}