Monday, March 23, 2009

GATE 2002 CS question 1.5 (Algorithm Analysis)

1.5 In the worst case, the number of comparisons needed to search a singly linked list of length n for a given element is:
(a) log n (b) n/2 (c) log2(n) - 1 (d) n


Here, we need to search for the element in a singly linked list. So, we can't use a search such as binary search, as we have no way of directly 'jumping' to the middle element.
Hence, log(n) is not possible.
n/2 would be the answer if they had asked for the average case.
However, here they're asking for the 'worst case'. The worst case in a singly linked list is when what we want to search for happens to be at the last of the list: then, we'd have to travel through the entire list to get to that element.
Hence, in the worst case, we'd have to do n comparisons - with each of the n elements of the list, before we finally find it.
So the answer is (d) n

No comments: