数据结构C语言版之查找(折半选择快速等)
生活随笔
收集整理的這篇文章主要介紹了
数据结构C语言版之查找(折半选择快速等)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
//查找:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
typedef struct{ int *elem;int length;
}SStable;
typedef struct SYlist{int num;int *Key;int *start;
}SYlist;
void CreatSearchlist(SStable &S)
{int i;printf("請輸入表長:\n");scanf("%d",&S.length);S.elem=(int*)malloc((S.length)*sizeof(int));for(i=1;i<S.length;i++)S.elem[i]=rand()%89+10;
}
int Search(SStable S,int key)
{S.elem[0]=key;while(S.elem[S.length]!=key)S.length--;return S.length;
}
void ShowSStable(SStable S)
{int i;for(i=1;i<S.length;i++)printf("%5d",S.elem[i]);printf("\n");
}
void Sort(SStable &S)
{int i,j,temp;for(i=1;i<S.length-1;i++){for(j=1;j<S.length-i-1;j++){if(S.elem[j]>S.elem[j+1]){temp=S.elem[j];S.elem[j]=S.elem[j+1];S.elem[j+1]=temp;}}}ShowSStable(S);
}
int Zbsearch(SStable S,int e)
{int mid,high=S.length-1,low=1;while(low<=high){mid=(low+high)/2;if(S.elem[mid]==e)return mid;else if(S.elem[mid]<e)low=mid+1;elsehigh=mid-1;}return 0;
}
void CreatSylist(SYlist &sy,SStable &S)
{int i,n;printf("\n\n\n建立索引表:\n");printf("請輸入數(shù)據(jù)個數(shù):\n");scanf("%d",&n);S.length=n+1;S.elem=(int*)malloc((S.length)*sizeof(int));printf("請輸入一組數(shù)(局部有序):\n");for(i=1;i<S.length;i++)scanf("%d",&S.elem[i]);printf("請輸入關(guān)鍵字個數(shù):\n");scanf("%d",&sy.num);sy.Key=(int*)malloc(sy.num*sizeof(int));sy.start=(int*)malloc(sy.num*sizeof(int));for(i=0;i<sy.num;i++){ printf("請輸入第%d個關(guān)鍵字:\n",i+1);scanf("%d",&sy.Key[i]);printf("請輸入該關(guān)鍵字的位置:\n");scanf("%d",&sy.start[i]);}
}
int Sysearch(SYlist sy,SStable S,int m)
{int i=0,j;while(m>sy.Key[i])i++;if(i>0 && i<sy.num-1){for(j=sy.start[i];j<sy.start[i+1];j++){if(S.elem[j]==m)return j;}}if(i==0){for(j=1;j<sy.start[1];j++){if(S.elem[j]==m)return j;}}if(i>=sy.num-1){for(j=sy.start[sy.num];j<S.length;j++){if(S.elem[j]==m)return j;}}
}
int main()
{SStable S;SYlist sy;int key,e,m;srand(time(0));CreatSearchlist(S);printf("隨機產(chǎn)生的%d個兩位數(shù)構(gòu)造的查找表為:\n",S.length-1);ShowSStable(S);printf("\n請輸入要查找的數(shù):");scanf("%d",&key);if(Search(S,key))printf("查找成功!該數(shù)在表中的位置為:%d\n",Search(S,key));elseprintf("查找失敗!\n");printf("對表中數(shù)據(jù)按遞增進行排序后的序列為:\n");Sort(S);printf("\n請輸入要查找的數(shù):");scanf("%d",&e);if(Zbsearch(S,e))printf("折半查找成功!該數(shù)在表中的位置為:%d\n",Zbsearch(S,e));elseprintf("查找失敗!\n");CreatSylist(sy,S);printf("\n請輸入要查找的數(shù):");scanf("%d",&m);Sysearch(sy,S,m);if(Sysearch(sy,S,m))printf("查找成功!該數(shù)在表中的位置為:%d\n",Sysearch(sy,S,m));elseprintf("查找失敗!\n");return 0;
}
轉(zhuǎn)載于:https://www.cnblogs.com/zhuhengjie/p/5966923.html
總結(jié)
以上是生活随笔為你收集整理的数据结构C语言版之查找(折半选择快速等)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux下去掉Windows文件的^M
- 下一篇: cms的使用与总结