読んだ後、シーケンシャルサーチとハーフサーチのアルゴリズムを学ぶことができないと思います


序文

Xiaobaiは注目を集めていますwoohoo!


1.順次検索を実装します

コードは次のとおりです(例):

#include<stdio.h>
#include<malloc.h>
#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++)
	   printf("%d",R[i].key);
	printf("\n");
}

#include"seqlist.cpp"
int SeqSearch(RecType R[],int n,KeyType k)
{
    
    
	int i=0;
	while(i<n&&R[i].key!=k)
	{
    
    
		printf("%d",R[i].key);
		i++;
	}
	if(i>=n)return 0;
	else
	{
    
    
		printf("%d",R[i].key);
		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);
	printf("关键字序列:");DispList(R,n);
	printf("查找%d所比较的关键字:\n\t",k);
	if((i=SeqSearch(R,n,k))!=0)
	   printf("\n元素%d的位置是%d\n",k,i);
	else
	   printf("\n元素%d不在表中\n",k);
	return 1;
}

ここに画像の説明を挿入

2.半分の検索を実現します

コードは次のとおりです(例):

#include<stdio.h>
#include<malloc.h>
#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++)
	   printf("%d",R[i].key);
	printf("\n");
}

#include"seqlist.cpp"
int BinSearch(RecType R[],int n,KeyType k)
{
    
    
	int low =0,high=n-1,mid,count =0;
	while(low<=high)
	{
    
    
		mid =(low+high)/2;
		printf("  第%d次比较:在[%d,%d]中比较元素R[%d];%d\n",
		++count,low,high,mid,R[mid].key);
		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];
	KeyType k=9;
	int a[]={
    
    1,2,3,4,5,6,7,8,9,10},i,n=10;
	CreateList(R,a,n);
	printf("关键字序列:");DispList(R,n);
	printf("查找%d的比较过程如下:\n",k);
	if((i=BinSearch(R,n,k))!=-1)
	   printf("元素%d的位置是%d\n",k,i);
	else
	   printf("元素%d不在表中\n",k);
	return 1;
}

ここに画像の説明を挿入


要約する

私は飛べない鳥です。この記事がお役に立てば、気に入ってフォローしてください。ありがとうございます。

おすすめ

転載: blog.csdn.net/A6_107/article/details/122141124
おすすめ