通過(guò)數(shù)組下標(biāo)對(duì)應(yīng)的值與要查找的數(shù)進(jìn)行比對(duì),中間下標(biāo)為最前面的0和數(shù)組實(shí)際長(zhǎng)度減一的平均值,如果要查找的值比中間下標(biāo)對(duì)應(yīng)的值大,
low=(中間下標(biāo)+1)徘跪,middle=(low+hight)/2;如果要查找的值比初始下標(biāo)對(duì)應(yīng)的值小琅攘,hight=中間下標(biāo)-1垮庐,middle=(low+hight)/2
運(yùn)行結(jié)果:
#include<stdio.h>
void binarySearch(int a[],int x);
int main(){
int arry[10]={1,3,6,7,9,11,14,15,17,24};
int x;
printf("請(qǐng)輸入要查找的數(shù):");
scanf("%d",&x);
binarySearch(arry,x);
}
void binarySearch(int a[],int x){
//查找?guī)状危谖恢?/p>
int count=0;//記錄次數(shù)
int low=0,hight=9;
int meddle;
int flag=0;
while(low<=hight){
count++;
meddle=(low+hight)/2;
if(x==a[meddle]){
printf("查找了%d次找到%d",count,x);
printf("\n%d的位置在%d\n",x,meddle);
flag=1;
break;//要加一個(gè)break坞琴,否則最后low一直小于等于hight 突硝。也可以用return
}
else if(x>a[meddle]){
low=meddle+1;
}
else{
hight=meddle-1;
}
}
if(flag==0){
printf("沒(méi)有找到");
}
}