Self-Organizing Linked List 1 Motivation • Searching for an element in a linked list takes O(N) worst case time – If we are lucky, and the element is at the beginning, then search is fast • Our goal is to try to keep elements that are likely to be searched in the near future close to the head – Methods vary in how they determine the nodes that need to be close to the head – The worst case search time in still O(N), but the average time can be much better – All linked list features, except search remain unchanged 2 Common Methods for Self-Organization • Move to front – After an element is found in a search, move it to the front • Transpose – After an element is found in a search, move it one step closer to the front • Count – Order the nodes by the number of times an element is searched • Ordering – Order by some other criterion, such as lexicographic order 3 Example Element searched or inserted Plain Move to Transpose front Count Lexical ordering A A A A A A C AC AC AC AC AC B ACB ACB ACB ACB ABC C ACB CAB CAB C-1AB ABC D ACBD CABD CABD C-1ABD ABCD A ACBD ACBD ACBD C-1A-1BD ABCD D ACBD DACB ACDB C-1A-1D-1B ABCD A ACBD ? ? ? ? C ACBD ? ? ? ? A ACBD ? ? ? ? Next, search for the following: C, C, E, E 4 Average Case Analysis • Usually, the time taken is neither the worst case time nor the best case time – Average case analysis assumes a probability distribution for the set of possible inputs and gives the expected time • tav = input i probability(i)time(i) – Average search time in a linked list • tav = probability(key is not present) n + i=1n probability(key is in node i) i • tav = n [1 - i=1n probability(key is in node i)] + i=1n probability(key is in node i) i 5 Average Case Analysis Example - 1 • Probability(i) = 1/n, 1 < i < n tav = n [1 - i=1n probability(key is in node i)] + i=1n probability(key is in node i) i = n [1 - i=1n 1/n] + i=1n 1/n i = n [0] + (1/n) i=1n i = (1/n) n(n+1)/2 = (n+1)/2 = O(n) 6 Average Case Analysis Example - 2 • Probability(i) = 1/(2n), 1 < i < n tav = n [1 - i=1n probability(key is in node i)] + i=1n probability(key is in node i) i = n [1 - i=1n 1/(2n)] + i=1n 1/(2n) i = n [1/2] + (1/(2n)) i=1n i = n/2 + (1/2n) n(n+1)/2 = n/2 + (n+1)/4 = O(n) 7 Average Case Analysis Example - 3 • Prob(1) = 0.5, prob(2) = 0.3, prob(3) = 0.2 tav = n [1 - i=1n probability(key is in node i)] + i=1n probability(key is in node i) i = n[1 - ] + 0.51 + 0.32 + 0.23 + i=4n 0i = n[0] + 0.5 + 0.6 + 0.6 + 0 = 1.7 = O(1) 8