/*-------------最佳置换算法(OPtimal Replacement Algorithm,ORA)-------------*/
/*算法描述:所选择的淘汰页,是以后永不使用,或最长时间内不使用的页面*/
/*---------------------------------writen by Xu Zhuozhuo-----------------------------------*/
C++代码示例:
#include <iostream>
#define MaxSize 20
#define Num_Block 3
using namespace std;
int max(int a,int b,int c) //返回三者的最大值
{
if(a<b) a=b;
if(a<c) a=c;
return a;
}
int main()
{
int num_ref; //引用字符的数目
int ref_arr[MaxSize]; //引用字符串数组
int phy_blk[Num_Block]; //数组模拟“物理块”
cout <<"-----Optimal Replacement Algorithms-----" <<endl <<endl;
do
{
cout <<"Please input the number of reference chars:" <<endl;
cin >>num_ref; //输入引用字符串的数目
}while(num_ref>MaxSize);
cout <<"Please input the queue of reference chars:" <<endl;
for(int i=0;i<num_ref;i++) //输入引用字符串的队列cin >>ref_arr[i];
for(int j=0;j<Num_Block;j++) //前Num_Block项进物理块phy_blk[j]=ref_arr[j];
cout <<endl <<"Display the replacement procedure: ";
cout <<endl <<"---------------------------------- " <<endl;
for(int p=0;p<num_ref-Num_Block;p++)
{
if(!(phy_blk[0]==ref_arr[Num_Block+p] ||
phy_blk[1]==ref_arr[Num_Block+p] ||
phy_blk[2]==ref_arr[Num_Block+p]))
{//寻找phy_blk[0]在引用字符串中的下一位置k1
for(int k1=Num_Block+p+1;k1<MaxSize;k1++)
if(phy_blk[0]==ref_arr[k1])
break;
//寻找phy_blk[1]在引用字符串中的下一位置k2
for(int k2=Num_Block+p+1;k2<MaxSize;k2++)
if(phy_blk[1]==ref_arr[k2])
break;
//寻找phy_blk[2]在引用字符串中的下一位置k3
for(int k3=Num_Block+p+1;k3<MaxSize;k3++)
if(phy_blk[2]==ref_arr[k3])
break;
int max_ref=max(k1,k2,k3); //返回k1,k2,k3中的最大者
if(max_ref==k1) //如果最大者为k1
phy_blk[0]=ref_arr[Num_Block+p];
else if(max_ref==k3) //如果最大者为k2
phy_blk[2]=ref_arr[Num_Block+p];
else if(max_ref==k2) //如果最大者为k3
phy_blk[1]=ref_arr[Num_Block+p];
}
//输出本次替换后的“物理块”数组内容
cout <<endl <<"[" <<p+1 <<"]. Physical block array content: ";
for(int loop=0;loop<Num_Block;loop++)
cout <<phy_blk[loop] <<" ";
}
return 0;
}
VC++6.0下的运行结果见下页:(数据源自操作系统课本)。