#include "stdio.h"
#include "malloc.h"
typedef int InfoType;
typedef int KeyType;
typedef struct{
KeyType key;
InfoType data;
} RecType;
////顺序查找
//int SeqSearch(RecType R[],int n,KeyType k){
// int i=0;
// while (i<n && R[i].key!=k)
// i++;
// if (i>=0)
// return 0;
// else return i+1;
//}
//int SeqSearch1(RecType R[],int n,KeyType k){
// int i=0;
// R[n].key=k;
// while (R[i].key!=k)
// i++;
// if (i==n)
// return 0;
// else return i+1;
//}
//折半查找
int BinSearch(RecType R[],int n,KeyType k){
int low=0 ,high=n-1,mid;
while (low<=high){
mid=(low+high)/2;
if (k==R[mid].key)
return mid+1;
if (k<R[mid].key)
high=mid-1;
else low=mid+1;
}
return 0;
}
//折半查找的扩展
int BinSearch2(RecType R[],int n,KeyType k){
int low=0 ,high=n-1,mid;
while (low<=high){
mid=(low+high)/2;
if (k<=R[mid].key){
high=mid-1;
} else low=mid+1;
}
return high+1;
}
int main(){
RecType a[]={1,1,2,2,3,3,4,4,5,5,6,6
,7,7,8,8,9,9};
printf("实验内容: 编写一个程序exp4-1.cpp,输出在顺序表(1,2,3,4,5,6,7,8,9,10)中采用折半查找方法查找关键字9的过程。\n");
printf( "结果的位置是%d。\n",BinSearch(a,9,9));
}
输出:
实验内容: 编写一个程序exp4-1.cpp,输出在顺序表(1,2,3,4,5,6,7,8,9,10)中采用折半查找方法查找关键字9的过程。
结果的位置是9。
发表回复