Algorithm: Linear Search For Array


In Linear Search algorithm whole array is traversed to search the element untill the element found.

Linear_Search(valArr[], n, searchValue)

Here valArr[] is of length n, and SearchValue  is a value which is to be found in the array. Consider lower bound of the array is 1. this algorithm will return index of first occurrence of the searchValue, and returns -1 on failure.

Step1: [Iterate the array]
           For index=1 to n repeat step 2 and 3

Step2:  if valArr[index]=searchValue then goto step 2(i) else goto step 3
                  i) return index

Step3: if index=n then goto step 3(i) else goto step 3(ii)
            i) return -1;
            ii) index=index-1;

Step4: End.




Explanation:
Suppose valArr is an array with the elements [10,23,12,14,18,19]. (Its size is n=6). Suppose we have to search element searchValue=14. 

when Index =1 

valArr:                         10          23        12            14           18             19

Search Value               14

Search Status:               X


When Index=2


valArr:                         10          23        12            14           18             19

Search Value                             14

Search Status:                             X



When Index=3


valArr:                         10          23        12            14           18             19

Search Value                                         14

Search Status:                                         X





When Index=4


valArr:                         10          23        12            14           18             19

Search Value                                                         14

Search Status:                                                         

return 4;


No comments:

Post a Comment