顺序表的各种查找方式的实现

在下看了某些书籍(例如零基础学数据结构)后,再加上自己的改造,写出了下面一段代码,可能有错,见谅

/    head.h   /
#include <iostream>
using namespace std;

#define MAXSIZE 100
#define INDEXSIZE 20
typedef int KeyType;

typedef struct 
{
KeyType key;
}DataType;

typedef struct 
{
DataType list[MAXSIZE];
int lenght;
}SSTable;

///引索顺序表的类型定义
typedef struct
{
KeyType maxkey;
int index;
}IndexTable[INDEXSIZE];


///   1一个挨着一个的找(效率慢)
int SeqSearch(SSTable S, DataType x)
{///在顺序表中查找关键字,如果找到放回表中所在位置
int i=0;
while( S.list[i].key!=x.key  &&  i<S.lenght )
{
i++;
}
if( S.list[i].key == x.key )
{
return i+1;    ///返回所在位置
}
else
{
return -1;   ///-1作为一个不存在的标志
}
}

///  2折半查找
int  BinarySearch(SSTable S, DataType x)
{
int low , high , mid;
low=0; 
high=S.lenght-1;

while(low<=high)
{
mid=(low+high)/2;
if( S.list[mid].key==x.key )
{
return mid+1;    ///为什么要加一呢?就是因为下表从零开始
}
else if( S.list[mid].key > x.key )
{
high=mid-1;
}
else if( S.list[mid].key <x.key )
{
low=mid+1;
}
}

return -1;  ///在上面找不到就返回-1(不存在标志)
}

///  引索顺序表的查找
int SeqIndexSearch(SSTable S, IndexTable T , int m, DataType x)
{///   m表示有多少块
int i,   j,   bl;
for(i=0; i<m; i++)
{
if( T[i].maxkey >= x.key )
{
break;
}
}
if( i>= m )
{
return -1;
}
j=T[i].index;
if( i<m-1 )
{
bl = T[i+1].index-T[i].index;
}
else
{
bl=S.lenght-T[i].index;
}
while( j<T[i].index+bl )
{
if( S.list[j].key == x.key )
{
return j+1;
}
else
j++;
}
return -1;
}

/   main.cpp   //
#include "head.h"

int SeqSearch(SSTable S, DataType x);
int  BinarySearch(SSTable S, DataType x);

void main()
{
SSTable s1={{12,234,546},3};
DataType find;
SSTable s2={ { 6,12,23,16,21,29,41,32,37,35,48,46,49,47,52,61,59,76,68,72 } , 20};
IndexTable t={ {23,0}, {41,5}, {52,10}, {76,15} };

cout<<"输入你想查找的元素:";
cin>>find.key;
if( SeqSearch(s1,find)==-1 )
{
cout<<"顺序表中不存在这个元素!"<<endl;
}
else
{
cout<<find.key<<"在表中的第 "<<SeqSearch(s1,find)<<" 个位置上。"<<endl;
}

if( BinarySearch(s1,find) ==-1 )
{
cout<<"顺序表中不存在这个元素!"<<endl;
}
else
{
cout<<find.key<<"在表中的第 "<<BinarySearch(s1,find)<<" 个位置上。"<<endl;
}

cout<<"输入你想用引索查找的数字:";
cin>>find.key;
if( SeqIndexSearch(s2,t,4,find) == -1 )
{
cout<<"不存在这个元素"<<endl;
}
else
{
cout<<find.key<<"在表中的第 "<<SeqIndexSearch(s2,t,4,find) <<" 个位置上。"<<endl;
}
}


上面代码很粗糙,不过包含简要的查找方法,看看就是了
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值