Is Sentinel Linear Search better than normal Linear Search?

Technology CommunityCategory: SearchingIs Sentinel Linear Search better than normal Linear Search?
VietMX Staff asked 3 years ago

In traditional linear search, there are n comparison for comparing with the required number and n+1 for looping condition, sums up to make 2n+1 comparisons. But, if we replace the last element of the list with the search element itself and run a while loop to see if there exists any copy of the search element, we can get our answer in n+2 comparisons at max. Note that both the algorithms have time complexity of O(n).

def sentinelSearch(ar,n,l):
    # ar : array
    # n : item to be searched
    # l : size of array
    last = ar[l-1] # saving last element in other variable
    ar[l-1] = n # assigning last element as required
    i = 0
    while ar[i]!=n:
        i+=1
    ar[l-1] = last
    if (i<l-1) or n==ar[l-1]:
        print('Item found at',i)
    else:
        print('Item not Found')

When considering Sentinel Search note:

  1. It’s not always possible to have a sentinel. For example modifying a shared array in a multithreaded context this way not safe. Or the array might be actually read-only for some reason.
  2. Compiler optimizations. Lots of time the loop over array gets unrolled and you actually do less than n comparisons for looping condition.
  3. Algorithm has to mutate the array (usually not good) and you have to keep special value for sentinel (not always possible).
  4. Will you ever notice any speed increase from this? No
  5. Will you notice a lack of readability? Yes
  6. Will you notice an unnecessary array mutation that might cause concurrency issues? Yes

So answering the question, the real benefit of the sentinel optimization would be really negligible and premature optimization is the root of all evil.