顺序查找和折半查找


顺序查找可以是线性表也可以是链表,同是既可以是有序的也可以是无序。

折半查找仅适用于有序的线性表

#include <stdio.h>
#include <stdlib.h>
#define ElemType int
typedef struct{
    ElemType *elem;
    int TableLen;
}SSTable;//表的数据结构
void CreatSS(SSTable *st){
    printf("表的长度:");
    scanf("%d",&st->TableLen);
    st->elem=(ElemType*)malloc(st->TableLen*sizeof(ElemType));
    ElemType *p=st->elem;
    printf("输入数据:");
    for(int i=0;i<st->TableLen;i++){
        scanf("%d",p);
        p=p+1;
    }
}//创建线性表
void PrintSS(SSTable *st){
    printf("顺序表:");
    ElemType *p=st->elem;
    for(int i=0;i<st->TableLen;i++){
        printf("%d ",*p);
        p=p+1;
    }
    printf("\n");
}
void SearchSS(SSTable *st,ElemType key){
    ElemType *p=st->elem;
    int flag=0;
    for(int i=0;i<st->TableLen;i++){
        if(key!=*p){
            p=p+1;
        }
        else{printf("关键字的位置为:%d\n",i+1);flag=1;break;}//位置一般从1开始
    }
    if(flag==0){printf("未找到相应的关键字\n");}
}//一般线性表查找
void SearchBin(SSTable *st,ElemType key){
    int mid,low=0;
    int high=st->TableLen-1,flag=0;
    while(low<=high){
        mid=(low+high)/2;
        if(st->elem[mid]==key){flag=1;break;}
        else if(st->elem[mid]>key){high=mid-1;}
        else low=mid+1;
    }
    if(flag==0){printf("未找到相应的关键字\n");}
    else{printf("关键字的位置为:%d\n",mid+1);}//位置一般从1开始
}//折半查找
void main(){
    SSTable st;
    CreatSS(&st);
    PrintSS(&st);
    SearchSS(&st,16);
    SearchBin(&st,7);
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM