基于有序顺序表的折半搜索

#include<iostream>
using namespace std;
//*****************************************//
//实验内容 ,实现基于有序顺序表的折半搜索。 //
//*****************************************//

//SeqList.h
typedef int keytype;//keytype =int
typedef struct
{
	keytype key;
}RecNode;
class SeqList
{
public:
	SeqList (int MaxListSize=100);
	~SeqList(){delete[] data;}
	void CreateList(int n);//顺序表输入
	int SeqSearch(keytype k);
	int SeqSearch1(keytype k);t
	int BinSearch(keytype k,in low,int high);
	friend void BinInsert(SeqList &R,keytype x);//,infoType y);
	void PrintList();
private:
	int length;//实际表长
	int MaxSize;//最大表长
	RecNode *data;//一维动态数组
};
SeqList::SeqList(int MaxListSize)
{
	//构造函数
	MaxSize=MaxListSize;
	data=new RecNode[MaxSize++];
	length=0;
}
void SeqList::CreateList(int n)
{
	for (int i=1;i<=n;i++)
	cin>>data[i].key;
	length=n;
}
void SeqList::PrintList()
{
	//表输出
	for (int i=1;i<=length;i++)
	cout<<data[i].key<<" ";
	cout<<endl;
}
int SeqList::SeqSearch(keytype k)
{
	//R[0]作为哨兵,用R[0].key==k作为循环下界的终结条件
	data[0].key=k;//设置哨兵
	int i=length;//从后向前扫描
	while(data[i].key!=k)
	i--;
	return i;
}
int SeqList::SeqSearch1(keytype k)
{
	//有序表的顺序查找法
	int i=length;
	while (data[i].key>k)
	{
		i--;
	}
	if (data[i].key==k)
	{
		return i;
	}
	return 0;
}
int SeqList::BinSearch(keytype k,int low,int high)
{
	//在区间R[low~hight]内二分递归查找关键字值等于k的记录
	//low的初始值为1,high的初始值为n
	int mid;
	while (low<=high)
	{
		mid=(low+high)/2;
		if (data[mid].key==k)return mid;//查找成功,返回其下标
		if (data[mid].key>k)
			high=mid-1;
		else 
			low=mid+1;
	}
	return 0;
}

void BinInsert(SeqList &R,keytype x)
{
	int low=1,high=R.length,mid,inspace,i;
	int find=false;
	while (low<=high&&!find)
	{
		mid=(mid+high)/2;
		if (x<R.data[mid].key)high=mid-1;
		else if (x>R.data[mid].key)low=mid+1;
		else find=true;
	}
	if (find)inspace=mid;
	else inspace=low;
	for (i=R.length;i>=inspace;i--)
		R.data[i+1]=R.data[i];
	R.data[inspace].key=x;
	R.length++;
}


//main.cpp
#include "SeqList.h"
void main()
{
	int i=0;
	SeqList	R;
	R.CreateList(11);
	R.PrintList();
	for (int m=43;m<50;m=m+5)
	{
		i=R.SeqSearch1(m);
		if (i!=0)
			cout<<"找到"<<m<<",位置在"<<i<<"处。\n";
			else cout<<"没有找到"<<m<<"。\n";
	}
}


你可能感兴趣的:(算法,搜索,结构)