即折半查找:此方法要求待查找的列表必须是按照关键字大小有序排列的顺序表。
查找过程:将表中间位置记录,将表分成前、后两个子表,如果中间位置记录的关键字大小等于查找关键字,则查找成功;如果如果中间位置记录的关键字大小大于查找关键字,则继续查找前一个子表;否则,继续查找后一子表。继续以上过程,直至查找成功,或查找结束
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
//#define LIST_SIZE 2
#define OK 1
#define ERROR 0
typedef int KeyType;
typedef struct{
KeyType key;//顺序表元素值
}RecordType;
typedef struct{
RecordType *r;//数组r
int length;//顺序表长度
}RecordList;
int SetSeq(RecordList *L){
int i,j,temp;
printf("请输入线性表长度:");
scanf("%d",&(L->length));
printf("请输入线性表中元素:");
L->r=(RecordType*)malloc((L->length+1)*sizeof(RecordType));//动态分配数组存储空间为L->length+1
for(i=1;i<=L->length;i++){
scanf("%d",&(L->r[i].key));//为地址为1到L->length数组元素赋值
}
return 0;
}
int SortSeq(RecordList *L){
int i,j,temp;
for(i=1;i<=L->length;i++){//对顺序表中的元素进行排序,形成递增序列
for(j=1;j<=L->length-i;j++){
if(L->r[j].key>L->r[j+1].key){//若第j个元素值大于第j+1个元素,交换两个元素值
temp=L->r[j].key;
L->r[j].key=L->r[j+1].key;
L->r[j+1].key=temp;
}
}
}
for(i=1;i<=L->length;i++){
printf("%d ",L->r[i].key);
}
return 0;
}
int SearchSeq(RecordList *L,KeyType k){
/**
*
*/
int low,mid,high;
low=1;
high=L->length;
//mid=(low+high)/2;
while(high>=low){
mid=(low+high)/2;
if(k>L->r[mid].key){//在mid位置的右边
low=mid+1;
}
if(k<L->r[mid].key){//在mid位置的左边
high=mid-1;
}
if(k==L->r[mid].key){
return mid;
}
}
return 0;
}
int main() {
//value为需要查找的值,position为元素所在位置
RecordList a;
KeyType value;
int position=0;
SetSeq(&a);
printf("对顺序表中元素进行排序后:");
SortSeq(&a);
printf("\n");
printf("请输入要查找的值:");
scanf("%d",&value);
printf("值为%d的元素的位置为:",value);
position=SearchSeq(&a,value);
if(position!=0){
printf("%d ",position);
}
else printf("未找到");
printf("\n");
return 0;
}
28万+

被折叠的 条评论
为什么被折叠?



