最近最久未使用页面淘汰算法———LRU算法(java实现)

请珍惜小编劳动成果,该文章为小编原创,转载请注明出处。


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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光光-Leo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值