Professional Documents
Culture Documents
Linear Search
Linear Search
with
C++
Sequential/Linear Search
• A search algorithm finds a specified item (key) among a given collection (e.g. array/linked list).
• Sequential/linear search systematically enumerates all possible candidates in the given collection and
compares them with the specified key.
• We start from first element in the collection, and visit each element to see if it matches the key.
• The elements in the given list may not follow any relative ordering (sorted or unsorted).
• Linear Search is:
- simple to implement
- complete (will always find a solution if one exists)
- typically used when the underlying data structure (linked list/array) or the relative ordering of the
elements (sorted/unsorted) is not specified
Iterative Linear Search
Linear Search: Given a list of n elements find whether a given element (key) exists in the list
0 1 2 3 4 5 6
a 31 67 59 43 71 48 54
= 71
key 71 71 71 71 71
Recursive Linear Search
Linear Search: Given a list of n elements find whether a given element (key) exists in the list
05 if (pos == -1)
06 cout << key << " NOT found" << endl;
07 else
08 cout << key << " found at index " << pos << endl;
09 return 0;
10 }