Algorithm to implement linear search for Data Structure

Algorithm to implement linear search:

LINEAR SEARCH (arr, n, key)
[ ‘arr’ is one-dimensional array of size ‘n’, key is element to search ]
success <-- FALSE
[Assuming the lower bound of the array as 1]
I<--1
Repeat While (I<=n) AND (success = FALSE)
  If (arr[I] = key) Then:
    success <--TRUE
  [End of If]
  I<--I+1
[End of While]
Return success
Exit.
     In this algorithm initially we assume that the search is unsuccessful by initializing a variable success as FALSE. Then we start the comparison of key from the first element by initializing the index variable I with 1. If the key is equal to first element then success is assigned with TRUE, which terminates the while loop. When the while loop is terminated the algorithm returns success as either TRUE or FALSE depending on the assignment. Similar comparisons are done with all the elements of the array by incrementing the index variable.

Comments

Popular posts from this blog

difference between structure and union in C Language

Difference between Linear search and Binary Search in c language

Difference between static and dynamic websites