資源描述:
《查找算法的實現(xiàn).doc》由會員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在應(yīng)用文檔-天天文庫。
1、(一)順序查找#include#defineMAX100typedefintkeytype;typedefstruct{keytypekey;}elemtype;typedefstruct{elemtypeelem[MAX+1];intlength;}SStable;voidcreate_seq(SStable*list);intseq_search(SStable*list,keytypek);voidmain(){SStable*list,table;keytypekey;inti;list=&table;printf("請輸入順序表的
2、長度:");scanf("%d",&list->length);create_seq(list);printf("創(chuàng)建的順表內(nèi)容:");for(i=0;ilength;i++)printf("list.elem[%d].key=%d",i+1,list->elem[i].key);printf("輸入查找關(guān)鍵字:");scanf("%d",&key);seq_search(list,key);}voidcreate_seq(SStable*list){inti;printf("請輸入順序表的內(nèi)容:");for(i=0;i3、>length;i++){printf("list.elem[%d].key=",i+1);scanf("%d",&list->elem[i].key);}}intseq_search(SStable*list,keytypek){inti=0,flag=0;while(ilength){if(list->elem[i].key==k){printf("查找成功.");flag=1;printf("list.elem[%d].key=%d",i+1,k);}i++;}if(flag==0)printf("沒有找到數(shù)據(jù)%d!",k);
4、return(flag);}(二)折半查找#include#defineMAX100typedefstruct{intelem[MAX+1];intlength;}Stable;voidcreat_seq(Stable*list);intsort_seq(Stable*list);intbin_search(Stable*list,intk,intlow,inthigh);voidmain(){Stable*list,table;inti,key;list=&table;printf("請輸入線性表的長度:");scanf("%d",&li
5、st->length);creat_seq(list);sort_seq(list);printf("請輸入查找的值:");for(i=1;i<=list->length;i++)printf("list.elem[%d].key=%d",i,list->elem[i]);printf(":");scanf("%d",&key);bin_search(list,key,1,list->length);}voidcreat_seq(Stable*list){inti;printf("請輸入順序表的內(nèi)容:");for(i=1;i<=list->l
6、ength;i++){printf("list.elem[%d].key=",i);scanf("%d",&list->elem[i]);}}intsort_seq(Stable*list){inti,j,flag;for(i=1;i<=list->length;i++){flag=0;for(j=1;jlength-i+1;j++)if(list->elem[j]>list->elem[j+1]){list->elem[0]=list->elem[j+1];list->elem[j+1]=list->elem[j];list->elem[j]
7、=list->elem[0];flag=1;}if(flag==0)return1;}}intbin_search(Stable*list,intk,intlow,inthigh){intmid;if(low>high){printf("沒有找到要查找的值");return(0);}mid=(low+high)/2;if(list->elem[mid]==k){printf("查找成功");printf("list[%d]=%d",mid,k);return(mid);}elseif(list->elem[mid]8、arch(list,k,mid+1,high));e