静态查找表的建立及顺序查找操作

来源:互联网 发布:滑板价格淘宝网 编辑:程序博客网 时间:2024/05/21 07:53
       查找是数据结构中很重要的一部分,最近在看查找表,首先是静态查找表,静态查找表可以以顺序表和线性链表来表示,用Search函数来顺序查找,从表中最后一个记录开始,逐个进行记录的关键字和给定值进行比较,如果相等,则查找成功,找到所查记录,反之,若直至最后一个记录,则查找不成功。
    另外,如果查找表是有序表的时候,Search函数可以用折半查找来实现。  折半查找只限于有序表,顺序存储结构。
以下是顺序表为存储结构的一个查找表。

/*****************************静态查找表的建立及顺序查找操作******************************///by vipper.zhang 2011.7.10 如果有什么问题或者可以改进的建议,请发邮件至vipper.zhang@gmail.com //O(∩_∩)0#include "stdafx.h"#include <iostream>#include <string>using namespace std;typedef int KeyType;//元素类型typedef struct {KeyType key;string   data;}ElemType;//查找表typedef struct{ElemType *elem;int length;} SSTable;//创建查找表void Create(SSTable &st,int len){ElemType *p=new ElemType[len+1];    //第一个元素用作监视哨    st.elem=p;st.length =len;}//销毁查找表void Destroy(SSTable &st){delete [] st.elem ;}//顺序查找  性能最差的查找int Search_Seq(SSTable st,KeyType key){st.elem[0].key =key;int i=st.length;while(st.elem[i].key !=key){   i--;}return i;}int _tmain(int argc, _TCHAR* argv[]){    SSTable st;int st_len=5;Create(st,st_len);//查找表填充元素cout<<"there are "<<st_len<<"elements .   "<<"input element of the search table: "<<endl;for(int i=1;i<st_len+1;i++){ cin>>st.elem[i].key >>st.elem[i].data ;}int search=0;cout<<"pls input an element you want to search:  "<<endl;cin>>search;int location=Search_Seq(st,search);if(location==0){cout<<"no such element."<<endl;        system("pause");return 0;}elsecout<<"the element locate at "<<location<<"   and its data is  "<<st.elem[location].data<<endl;  Destroy(st);system("pause");return 0;}



测试用例: 1 a 2 b 3 c 4 d 5 e
查找元素: 3   6
原创粉丝点击