Category Archives: Page Replacement Algorithms

Optimal – Page Replacement Algo :

<br />#include
using namespace std;

int frame[3];
int opt[3];

int main()
{
int n,i,k=0,j=0,index=0,max=0,ph=0;
cout<<"\t------> Page Replacement Algorithm (Optimal) <------\n\n";
cout<<"Enter the no. of pages:\t"; cin>>n;

int pr[n];

cout<<"\nEnter Page Request:\n";
for(int j=0;j<n;j++) { cin>>pr[j];
}

for(i=0;i<3;i++)
{
opt[i]=-1;
frame[i]=-1;
}

for(int i=0;i<n;i++)
{
int has = 0;
for(int j=0;j<3;j++)
{
if(frame[j]==pr[i])
{
has=1;
cout<<"\t\t Page hit = "<< ++ph <<"\n";
}
}
if(has==0)
{
for(int j=0;j<3;j++)
{
for(int k=i+1;k<n;k++)
{
opt[j]=0;
if(frame[j]==pr[k])
{
opt[j]=k-i;
break;
}
}
}

int tag=0;
for(int j=0;j<3;j++)
{
if(opt[j]==0)
{
index=j;
tag=1;
break;
}
}
if(tag==0)
{
max=opt[0];
index=0;
for(int k=1;k<3;k++)
{
if(max<opt[k])
{
max=opt[k];
index=k;
}
}

}
frame[index]=pr[i];
}
cout<<"\nPages loaded are : ";
for(int k=0;k<3;k++)
cout<<frame[k]<<" ";
}
cout<<"\n Total page fault "<<(n-ph);
}

Output :-

Optimal - PRA
Optimal – PRA

 

Least Recently Used – Page Replacement Algo :

<br />#include<iostream>
using namespace std;

int lru[3];
int frame[3];

int main()
{
int n,i,j=0,small=0,ph=1;
cout<<"\t------> Page Replacement Algorithm (LRU) <------\n\n";
cout<<"Enter the no. of pages:\t";
cin>>n;

int pr[n];

cout<<"\nEnter Page Request:\n";
for(int j=0;j<n;j++)
{
cin>>pr[j];
}

for(i=0;i<3;i++)
{
lru[i]=-1;
frame[i]=-1;
}

int p=0;

while(p<n)
{
int has = 0;

for(i=0;i<3;i++)
{
if(frame[i]==pr[p])
{
has=1;
lru[i]=p;
cout<<"\t\t Page hit = "<<ph++ <<"\n";
}
}

if(has==0)
{

for(j=0;j<3;j++)
{
if(lru[j]<lru[small])
{
small=j;
}
}

lru[small] = p ;
frame[small] = pr[p];
}



cout<<"\npages loaded are : ";

for(int j=0;j<3;j++)
{
cout<<frame[j]<<" ";
}
p++;
}
cout<<"\n\nTotal Page faults = "<<(n-ph+1) ;
return 0;
}

Output :-
lru

First In First Out : Page Replacement Algo

<br />#include<iostream>
using namespace std;

int frame[3];

int main()
{
int n,i,flag,k=0,j=0;
cout<<"\t------> Page Replacement Algorithm (FIFO) <------\n\n";
cout<<"Enter the no. of pages:\t"; cin>>n;

int pr[n];

cout<<"\nEnter Page Request:\n";
for(int j=0;j<n;j++) { cin>>pr[j];
}

for(int i=0;i<3;i++)
{
frame[i]=-1;
}

int p=0,pf=1;

while(p<n)
{
flag=0;
for(i=0;i<3;i++)
{
if(frame[i]==pr[p])
flag=1;
}
if(flag==1)
cout<<"\t\t Hit:"<<pf++<<"\n\n";

if(flag==0)
{
frame[k%3]=pr[p];
k++;
}

cout<<"\n Frame :- ";
for(j=0;j<3;j++)
{
cout<<frame[j]<<" ";
}

p++;
}
cout<<"\n\nTotal Page hits are : "<<(pf-1);

return 0;
}

Output :-