algorithm - Is sentinel linear search better than normal linear search? -


in traditional linear search, there n comparison comparing required number , n+1 looping condition, sums make 2n+1 comparisons. but, if follow following procedure, can our answer in n+2 comparisons @ max.

def sentinelsearch(ar,n,l): # ar : array # n : item searched # l : size of array last = ar[l-1] # saving last element in other variable ar[l-1] = n # assigning last element required = 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') 

although, worst case time complexity of both algorithm o(n). number of comparisons reduced, make 'sentinel linear search' better algorithm searching on unsorted array or not?

you have benchmark it. there multiple factors, can influence result like:

  • branch prediction. checking conditions less expensive others.
  • compiler optimizations. lots of time loop on array gets unrolled , less n comparisons looping condition.

also people mentioned in comments, algorithm has mutate array (usually not good) , have keep special value sentinel (not possible). real benefit of optimization negligible.


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -