#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
#define COMPARE(x,y) (((x)<(y))?-1:((x)==(y))?0:1)
int binsearch(int list[],int searchnum,int left,int right);
void printArray(int list[],int arraySize);
int main()
{
int i,num;
int list[MAX_SIZE]={1,2,3,4,5,6,7,8,9,10};
printArray(list,MAX_SIZE);
printf("Enter the searnum:");
scanf("%d",&num);
int index=binsearch(list,num,0,MAX_SIZE-1);
printf("Your spected index is %d",index);
return 0;
}
int binsearch(int list[],int searchnum,int left,int right){
int middle;
while(left<=right){
middle=(left+right)/2;
switch(COMPARE(list[middle],searchnum)){
case -1:
left=middle+1;
break;
case 0:
return middle;
case 1:
right=middle-1;
}
}
return -1;
}
void printArray(int list[],int arraySize){
int i;
for(i=0;i<arraySize;i++){
printf("%d ",list[i]);
}
printf("\n");
}
二分查找
最新推荐文章于 2023-05-28 13:59:52 发布