例:在数组a = [46,30,82,90,56,17,95]中寻找 x = 17
start = 0,end = length(a) - 1,mid = (start + end)/2
如果30大于a[mid] = 90,由于我们是按递增顺序存储的,所以,30一定在mid的后面,则将start = mid+1;
如果30小于a[mid] = 90,则30一定在mid的前面,所以,将end= mid - 1;
如果30正好等于a[mid] = 90,则程序结束,返回mid。
注意:是mid+1或mid - 1,而不是mid。因为已经确定a[mid] ! = 17,所以mid已经不用再考虑了。当然,如果你写成了start = mid,结果也没错。
本例中30小于90,所以,将end移动到mid-1
此时a[mid] = 30,将mid返回,程序结束。
while (start <= end) {
注意:是<= ,不是<,这将影响比较的次数
二分查找算法代码
#include <iostream>
/*A为查找数组,x为查找元素,N为length(A) -1 */
int binarySearch(const int A[], int X, int N){
int start = 0, end = 0, mid;
end = N;
while (start <= end) {
mid = (start + end)/2;
if (X > A[mid]) {
start = mid+1;
continue;
}else if (X < A[mid]){
end = mid-1;
continue;
}else{
return mid;
}
}
return -1;
}
int main(int argc, const char * argv[])
{
int A[]={1 ,4 , 6, 8, 19, 34, 93};
int N = sizeof(A)/sizeof(int);
int X = 20;
for(int i = 0;i<N;i++){
printf("%d ",A[i]);
}
printf("\nFind:%d\n",X);
int locate = binarySearch(A, X, N);
if (locate == -1) {
printf("NO\n");
}else{
printf("Yes index:%d",locate);
}
return 0;
}
运行结果