順序查找和折半查找


順序查找可以是線性表也可以是鏈表,同是既可以是有序的也可以是無序。

折半查找僅適用於有序的線性表

#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