概率算法之Sherhood算法 有序表的查找

/*
 * Abstract:
 *         PPT67,EX7. 写一个Sherhood算法C,与算法A,B,D比较,给出实验结果
 *         实验结果说明,算法性能C>B>D>A
 * Author : Ace.Ma
 * Date   : 2012/9/18
 * Version: 0.1 
 */
#include<iostream>
#include<ctime>
#include<set>
#include<cmath>
using namespace std;

const int N = 15;
int val[N] = {RAND_MAX, 2, 3, 13, 1, 5, 21, 8, 29, 87, 56, 69, 72, 83, 45}; //N==15
int ptr[N] = {       4, 2, 5,  6, 1, 7,  8, 3, 14,  0, 11, 12, 13,  9, 10};
int ComCount=0; //用于Search算法查找需要的次数

//设x≥val[i]且x在表中,则从位置i开始查找x的算法
int Search(int x, int i)
{
	ComCount=0;
	while( x > val[i])
	{
		i = ptr[i];
		++ComCount;
	}
	return i;
}
//在表val[1..n]中从最小值开始查找x的算法为:
int A(int x)
{
	return Search(x,ptr[0]);
}



//在val数组的前sqrt(n)个元素中找y<=x的最大整数y,从y开始查找。
//在这里假设了val的元素是均匀分散的
int B(int x)
{
	int i = ptr[0];
	int max = val[i];
	for( int j=1; j <= (int)sqrt((double)N); ++j)
	{
		int y = val[j];
		if( max < y && y<=x )
		{
			i = j;
			max = y;
		}
	}
	return Search(x,i);
}

//随机选择val数组中的一个数做为开始,随机sqrt(n)次,选取y<=x的最大整数y,从y开始查找,
//此算法比B算法有更好的平均性能
int C(int x)
{
	int i = ptr[0];
	int max = val[i];
	for( int j=1; j <= (int)sqrt((double)N); ++j )
	{
		int k = rand()%N;
		int y = val[k];
		if( max < y && y<=x )
		{
			i = k;
			max = y;
		}
	}
	return Search(x,i);
}

//随机选一个指针位置(0~n-1)开始查找,本例n=8
int D(int x)
{
	int i = rand()%N; //C++ 从零开始,最后不必加1 
	int y = val[i];
	if (x < y)
	{
		return Search(x, ptr[0]);
	}else if( x > y){
		return Search(x, ptr[i]);
	}else{
		return i;
	}

}
int main()
{
	int totalA=0;
	int totalB=0;
	int totalC=0;
	int totalD=0;
	int i =0;
	//对有序表中的元素逐个进行查找,得出所用的总比较次数。
	int temp(1);
	while( ptr[i] != 0 )
	{
		A(val[ptr[i]]);
		totalA += ComCount;
		B(val[ptr[i]]);
		totalB += ComCount;
		C(val[ptr[i]]);
		totalC += ComCount;
		D(val[ptr[i]]);
		totalD += ComCount;
		i = ptr[i];
		temp++;
	}
	cout<<"对有序表中的元素逐个进行查找,得出所用的总比较次数。\n遍历的元素表中的个数N="<<temp<<endl<<endl;
	cout<<"算法A比较总次数:"<<totalA<<endl;
	cout<<"算法B比较总次数:"<<totalB<<endl;
	cout<<"算法C比较总次数:"<<totalC<<endl;
	cout<<"算法D比较总次数:"<<totalD<<endl;
    system("pause");
	return 0;
    
} 



实验结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值