Hacking the O(n) Find

Recall we can use a heuristic that moves the target of a search to the head of a list so it is found faster next time. This technique is called “move-to-front heuristic”. It speeds up linear search performance in linked list, if the target item is likely to be searched for again soon.

Exercise Can we apply the move-to-front heuristic to speed up linear search in an array?


Maybe! Moving the target of a search to the front of an array requires shifting all the other elements to the right. This is an additional linear time operation (in addition to the linear search).

Please watch the video lecture where some of the students brilliantly came up with ideas to keep this a constant time operation (at the cost of more complex implementations such as circular array).

A more common strategy is “transpose sequential search” heuristic.

Note: think about why it would not be a good idea to implement “move-to-front” heuristic in an array but instead of “moving” the target element to the front, swapping it with the front value.