在下看了某些书籍(例如零基础学数据结构)后,再加上自己的改造,写出了下面一段代码,可能有错,见谅
/ 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;
}
}
上面代码很粗糙,不过包含简要的查找方法,看看就是了