顺序查找,折半查找
顺序查找
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct{
ElemType *data;
int lengh;
}T;
int main(){
T t;
int i;
int data[10]={0,1,2,3,4,5,6,7,8,9};
t.data=data;
t.lengh=10;
for(i=0;i<t.lengh&&t.data[i]!=5;i++);
printf("%d",i==t.lengh? -1:i);
char ca;
scanf("%c",&ca);
}
折半查找
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct{
ElemType *data;
int lengh;
}T;
int main(){
T t;
int s=8;
int low=0,high=9;
int data[10]={0,1,2,3,4,5,6,7,8,9};
t.data=data;
t.lengh=10;
while(low<=high){
if(t.data[(low+high)/2]==s){
return (low+high)/2;
}
else if(t.data[(low+high)/2]>s){
high=((low+high)/2)-1;
}else{
low=((low+high)/2)+1;
}
}
return -1;
}