/*
* 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;
}
实验结果: