顺序表查找的基本知识

在下刚刚学习这个顺序表的排序,所以这段程序写的不咋的,见谅!

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

#define MAXSIZE 20

struct dataType
{
int key;       //////以整型作为查找的类型
};
typedef dataType DataType;

struct Node
{
DataType *elem;
int lenght;
};
typedef Node SSTable;

///初始化顺序表
void initList(SSTable &S)
{
S.elem = (DataType *) malloc (MAXSIZE * sizeof(DataType) );   ///首先分配一个地址
if( ! S.elem )
{
exit(-1);
}
S.lenght=0;     ///初始化长度为零(因为现在还是没有元素的)
}

bool insertList(SSTable &S, int i ,DataType d)
{//////////////////////////i代表插入的位置
DataType  *p,*q;

if( i<0 || i>S.lenght+1)
{
return false;
}
if( S.lenght > MAXSIZE )
{
S.elem=( DataType *)malloc( (MAXSIZE+10)*sizeof( DataType) );
if( !S.elem )
{
return false;
}
}

q=&(S.elem[i-1]);
for( p=&( S.elem[S.lenght-1] )  ; p>=q ; --p)
{
*(p+1)=*p;
}
*q=d;
++S.lenght;

return true;
}

void showList(SSTable S)
{
for(int i=0; i<S.lenght-1; i++)
{
cout<<S.elem[i].key<<"   ";
}
cout<<endl;
}

///顺着表一个一个查询
int search(SSTable S, DataType D)
{
int i=0;
while(  (S.elem[i].key!=D.key)  &&  (i<=S.lenght) )
{
i++;
}
if( i<=S.lenght )
{
return i+1;
}
else
{
return -2;
}
}

///顺着表一个一个查询2(设置一个哨兵)
int search2(SSTable S, DataType D)
{
int i =S.lenght;
int key=S.elem[0].key;     ///////把第一个元素当作哨兵
while( (S.elem[i].key != D.key) && ( i>=0 ))
{
--i;
}
if( i>=0 )
{
return i+1;
}
else
{
return -2;
}

}

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

void initList(SSTable &S);
bool insertList(SSTable &S, int i ,DataType d);
void showList(SSTable S);
int search(SSTable S, DataType D);
int search2(SSTable S, DataType D);

void main()
{
SSTable S;
initList(S);
DataType find;

for( int i=0; i<10;  i++)
{
DataType d;
d.key=i*2;
insertList(S,i,d);
}
showList(S);

cout<<"输入你要查找的元素:";
cin>>find.key;
if( search(S,find)!=-2 )
{
cout<<find.key<<"在第 "<<search(S,find)<<" 个位置上!"<<endl;
}
else
{
cout<<"不存在这个元素"<<endl;
}
/////////////尝试第二中查询方法
if( search2(S,find)!=-2 )
{
cout<<find.key<<"在第 "<<search2(S,find)<<" 个位置上!"<<endl;
}
else
{
cout<<"不存在这个元素"<<endl;
}
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值