本文以序列長度20的{ 7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1};以及頁面4;為例;
1 #include <stdio.h> 2 3 #define InitPysiBlocks 4 4 #define MaxPages 20 5 int PysicalBlocks[InitPysiBlocks] = { -1,-1,-1,-1 }; 6 int PageSequence[MaxPages] = { 7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1}; 7 8 void LRU(int py[],int pg[]) 9 { 10 int i,j,k,m,flag[MaxPages],temp[MaxPages][InitPysiBlocks]; 11 int max = 0; 12 char f[MaxPages]; 13 for(i = 0; i < InitPysiBlocks; i++) 14 { 15 py[i] = pg[i]; 16 flag[i] = i; 17 f[i] = '*'; 18 for(j = 0; j < InitPysiBlocks; j++) 19 temp[i][j] = py[j]; 20 } 21 for(i = InitPysiBlocks; i < MaxPages; i++) 22 { 23 for(j = 0,k = 0; j < InitPysiBlocks; j++) 24 { 25 if(py[j] != pg[i]) 26 k++; 27 else 28 flag[j] = i; 29 } 30 if(k == InitPysiBlocks) 31 { 32 f[i] = '*'; 33 max = flag[0] < flag[1]?0:1; 34 for(m = 2; m < InitPysiBlocks; m++) 35 if(flag[m] < flag[max]) 36 max = m; 37 py[max] = pg[i]; 38 flag[max] = i; 39 for(j = 0; j < InitPysiBlocks; j++) 40 temp[i][j] = py[j]; 41 } 42 else 43 { 44 f[i] = ' '; 45 for(j = 0; j < InitPysiBlocks; j++) 46 temp[i][j] = py[j]; 47 } 48 } 49 printf("輸出結果為下表(-1代表為空,*代表有缺頁):\n"); 50 for(i = 0; i < InitPysiBlocks; i++) 51 { 52 for(j = 0; j < MaxPages; j++) 53 printf("%3d",temp[j][i]); 54 printf("\n"); 55 } 56 for(i = 0; i < MaxPages; i++) 57 printf("%3c",f[i]); 58 printf("\n"); 59 } 60 61 void main() 62 { 63 LRU(PysicalBlocks,PageSequence); 64 }
測試: