Understanding LRU Algorithm

user249375 picture user249375 · Nov 12, 2012 · Viewed 9.3k times · Source

I am trying to understand LRU and its making no sense to me. If I understand it then it will be easier for me to code. Can someone walk me through the steps? Like,

  1. If the reference string you are currently at is in the array then do you increment to the next space?
  2. When you check to see if somethings in the buffer then do we need to scan where we are at or the whole array?

I just cant seem to follow along. How is it keeping track of least recently used? Shouldnt the least recently used be the one after the index your at?

enter image description here

Answer

Cory Nelson picture Cory Nelson · Nov 12, 2012

An LRU is typically put in a list. When an item is accessed, remove it from the list (if it's there), and push it to the back. The back of the list is the Most Recently Used. Because you're continually moving used items to the back of the list, the least used ones end up naturally at the front of the list. When there's not enough room, you pop from the front.