請珍惜小編勞動成果,該文章為小編原創,轉載請注明出處。
LRU算法,即Last Recently Used ---選擇最后一次訪問時間距離當前時間最長的一頁並淘汰之——即淘汰最長時間沒有使用的頁
按照最多5塊的內存分配情況,實現LRU算法代碼如下:
public class LRU {
private int theArray[];
private int back; //定義隊尾
private int currentSize; //隊列中存放元素個數
private int maxSize=5; //隊列中能存放元素的個數
public LRU(){
theArray=new int[maxSize];
back=0;
currentSize=0;
}
public void queue(int a[]){
for(int i=0;i<a.length;i++){
enQueue(a[i]);
}
}
public void enQueue(int x){ //入隊
beUsed(x); //先判斷是否已存在該頁號,若存在,刪除
if(currentSize<maxSize){
theArray[back]=x;
back++;
currentSize++;
}else if(currentSize==maxSize){ //滿了
for(int i=0;i<maxSize-1;i++){
theArray[i]=theArray[i+1];
}
theArray[maxSize-1]=x;
}
for(int i=0;i<currentSize;i++){
System.out.print(theArray[i]);
}
System.out.println();
}
public void beUsed(int x){ //判斷是否已存在該頁號,若存在,刪除已有的
for(int i=0;i<currentSize;i++){
if(theArray[i]==x){
for(int j=i;j<currentSize-1;j++){
theArray[j]=theArray[j+1];
}
currentSize--;
back--;
}
}
}
public static void main(String[] args) {
LRU lru=new LRU();
int a[]={4,7,0,7,1,0,1,2,1,2,6};
lru.queue(a);
}
}
測試結果如下:
4
47
470
407
4071
4710
4701
47012
47021
47012
70126
版權聲明:本文為博主原創文章,未經博主允許不得轉載。
