Optimal page replacement algorithm


SUBMITTED BY: Guest

DATE: Nov. 12, 2013, 2:46 a.m.

FORMAT: Text only

SIZE: 2.1 kB

HITS: 804

  1. #include<iostream>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<ctype.h>
  5. using namespace std;
  6. int maxdis(int *dis,int max)
  7. {
  8. int m=0;
  9. for(int i=0;i<max;i++)
  10. {
  11. if(dis[i]>dis[m]) m=i;
  12. }
  13. return(m);
  14. }
  15. int found(int x,int *l,int j)
  16. {
  17. for(int i=0;i<j;i++)
  18. if(l[i]==x){return(i);}
  19. return(-1);
  20. }
  21. int found1(int x,int *temp,int max)
  22. {
  23. for(int i=0;i<max;i++)
  24. if(temp[i]==x) return(i);
  25. return(-1);
  26. }
  27. int main()
  28. {
  29. cout<<"\n\nEnter the maximum number of frames in the main memory:\t";
  30. int max;
  31. cin>>max;
  32. int *temp=new int[max];
  33. int *dis=new int[max];
  34. int *flag=new int[max];
  35. for(int i=0;i<max;i++) flag[i]=0;
  36. cout<<"\n\nEnter the total number of page requests:\t";
  37. int n,res;
  38. cin>>n;
  39. cout<<"\n\nEnter the entire sequence of page requests:\t";
  40. int *a=new int[n];
  41. for(int i=0;i<n;i++) a[i]=-1;
  42. for(int i=0;i<n;i++) cin>>a[i];
  43. cout<<"\n\nprocess pages are then allocated as follows:\n\n";
  44. int j=0;
  45. for(int i=0;i<max;)
  46. {
  47. cout<<"\n\npage "<<a[j]<<" has been allocated frame "<<i<<" in MM";
  48. if((res=found(a[j],temp,i))!=-1) {cout<<"\n\npage "<<a[j]<<" already exists in frame "<<res<<" in MM";j++;}
  49. else {j++;temp[i++]=a[i];}
  50. }
  51. for(int i=j;i<n;i++)
  52. {
  53. for(int z=0;z<max;z++) flag[z]=0;
  54. if((res=found1(a[i],temp,max))!=-1) {cout<<"\n\npage already exists in frame "<<res<<" in MM";continue;}
  55. cout<<"\n\npage fault has occured";
  56. for(int x=0;x<max;x++)
  57. for(int y=i+1;y<n;y++)
  58. {
  59. if(temp[x]==a[y] && flag[x]==0) {dis[x]=y;flag[x]=1;}
  60. else if(flag[x]!=1) dis[x]=1000000;
  61. }
  62. int pos=maxdis(dis,max);
  63. cout<<"\n\npage "<<a[i]<<" has been allocated frame "<<pos<<" in MM by replacing page "<<temp[pos];
  64. temp[pos]=a[i];
  65. }
  66. delete[] temp;
  67. delete[] dis;
  68. delete[] flag;
  69. delete[] a;
  70. return(0);
  71. }

comments powered by Disqus