Take note that both the algorithms have time complexity of O(n). Which is better than ( 2N+1 ) comparisons as found in Simple Linear Search. So in the worst case ( if the search element does not exists in the list ) then there will be at most N+2 comparisons ( N comparisons in the while loop and 2 comparisons in the if condition). Here we see that the while loop makes only one comparison in each iteration and it is sure that it will terminate since the last element of the list is the search element itself. See the code snippet for clarification.Īrray = item // Here item is the search element. Here 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 in the list and quit the loop as soon as we find the search element. Sentinel Linear Search : Here the idea is to reduce the number of comparisons required to find an element in a list. Now considering the worst case in which the search element does not exist in the list of size N then the Simple Linear Search will take a total of 2N+1 comparisons ( N comparisons against every element in the search list and N+1 comparisons to test against the end of the loop condition). Repeat this, till you find an element.Linear Search : The idea behind linear search is to compare the search item with the elements in the list one by one (using a loop) and stop as soon as we get the first copy of the search element in the list. If the element is less than then move to the right of the list or if the element is greater than then move to the left of the list. If the element is equal to the element that we are searching then return true. As we know binary search is applied on sorted lists only for fast searching.įor example, if searching an element 25 in the 7-element array, following figure shows how binary search works:īinary searching starts with middle element.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |