线性查找
示例代码:
#include<stdio.h>
char a[]="hello world";
int indexof(char letter){
int i=0;
while(a[i]!='\0'){
if(a[i]==letter){
return i;
}
i++;
}
}
int main(void){
printf("fuck:%d %d\n",indexof('o'),indexof('z'));
return 0;
}
折半查找
#include<stdio.h>
#define LEN 8
int a[LEN]={1,2,2,2,5,6,8,9};
int binarysearch(int num){
int mid,start=0,end=LEN-1;
while(start<=end){
mid=(start+end)/2;
printf("%d\n",mid);
if(a[mid]<num){
start=mid+1;
}else if(a[mid]>num){
end=mid-1;
}else{
return mid;
}
}
return -1;
}
int main(void){
printf("%d\n",binarysearch(5));
return 0;
}