实验八 查找

实验题1:编写一个程序,输出在顺序表(3,6,2,10,1,8,5,7,4,9)中采用顺序查找方法查找关键字5的过程。

#include<stdio.h>
#include<malloc.h>
#include<iostream>
using namespace std;
#define MAXL 100

typedef int KeyType;
typedef char InfoType;
typedef struct
{
	KeyType key;
	InfoType data;
} RecType;

void CreateList(RecType R[],KeyType keys[],int n)
{
	for(int i=0;i<n;i++)
	{
		R[i].key=keys[i];
	}
}

void DispList(RecType R[],int n)
{
	for(int i=0;i<n;i++)
	    cout<<R[i].key<<" ";
    cout<<endl;
}

int SeqSearch(RecType R[],int n,KeyType k)
{
	int i=0;
	while(i<n&&R[i].key!=k)
	{
		cout<<R[i].key<<"→";
		i++;
	}
	if(i>=n) return 0;
	else
	{
		cout<<R[i].key<<endl;
		return i+1;
	}
}

int main()
{
	RecType R[MAXL];
	int n=10,i;
	KeyType k=5;
	int a[]={3,6,2,10,1,8,5,7,4,9};
	CreateList(R,a,n);
	cout<<"关键字序列:";
	DispList(R,n);
	cout<<"查找关键字"<<k<<endl;
	if((i=SeqSearch(R,n,k))!=0)
	    cout<<"关键字的位置是:"<<i<<endl<<endl;
    return 0;
}

实验题2:编写一个程序,输出在顺序表(1,2,3,4,5,6,7,8,9,10)中采用折半查找方法查找关键字9的过程。

#include<stdio.h>
#include<malloc.h>
#include<iostream>
using namespace std;
#define MAXL 100

typedef int KeyType;
typedef char InfoType;
typedef struct
{
	KeyType key;
	InfoType data;
} RecType;

void CreateList(RecType R[],KeyType keys[],int n)
{
	for(int i=0;i<n;i++)
	{
		R[i].key=keys[i];
	}
}

void DispList(RecType R[],int n)
{
	for(int i=0;i<n;i++)
	    cout<<R[i].key<<" ";
    cout<<endl;
}


int BinSearch(RecType R[],int n,KeyType k)
{
	int low=0,high=n-1,mid,count=0;
	while(low<=high)
	{
		mid=((low+high)/2);
		cout<<"第"<<++count<<"次比较:在第"<<low+1<<"-"<<high+1 
		<<"个元素中与元素"<<R[mid].key<<"进行比较"<<endl;
		if(R[mid].key==k)
		    return mid+1;
        if(R[mid].key>k)
            high=mid-1;
        else low=mid+1;
	}
	return 0;
}

int main()
{
	RecType R[MAXL];
	int n=10,i;
	KeyType k=9;
	int a[]={1,2,3,4,5,6,7,8,9,10};
	CreateList(R,a,n);
	cout<<"关键字序列:";
	DispList(R,n);
	cout<<"查找关键字"<<k<<endl;
	if((i=BinSearch(R,n,k))!=-1)
	    cout<<"关键字的位置是:"<<i<<endl<<endl;
    return 0;
}

仅作留档。

发布了30 篇原创文章 · 获赞 12 · 访问量 876

猜你喜欢

转载自blog.csdn.net/weixin_43893854/article/details/104326434