1.折半查找又称二分查找,它仅适用于有序的顺序表(注:折半查找不适合链表,因为顺序表拥有随机访问的特性,而链表没有)。
2.折半查找可以采用非递归算法,也可以采用递归算法。下面就用代码分别实现两种算法:
#define maxSzize 10000;
typedef struct seqList
{
int data[maxSzize];
int length;
};
int midSearch(seqList L,int key)
{
int low=0,mid,high=L.length-1;
while(low<=high)
{
mid=(low+high)/2;
if(L.data[mid]==key)
{
return mid;
}else if(L.data[mid]>key){
high=mid-1;
}else{
low=mid+1;
}
}
return 0;
}
#define maxSzize 10000;
typedef struct seqList
{
int data[maxSzize];
int length;
};
int midSearch(seqList L,int key,int low,int high)
{
if(low>high)
{
return 0;
}
if(key>L.data[mid])
{
midSearch(L,key,mid+1,high);
}else if(key<L.data[mid])
{
midSearch(L,key,low,mid-1);
}else{
return mid;
}
}
|