You are on page 1of 6

Data Structures

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

01 void linearSearch(a[], int l, int r, int key) {


02 for (int i = l; i <= r; i++) {
03 if (a[i] == key)
04 return i;
05 return -1;
06 }

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

01 int linearSearch( a[], int l, int r, int key) {


02 if (l > r) return -1;
03 if (a[l] == key) return l;
04 return linearSearch(a, l + 1, r, key);
05 } ❸ 2nd Recursive Call
linearSearch
= 72 a = {76, 67, 72, 81, 49}
key l =2 Base case
r =4 returns l = 2
❷ 1st Recursive Call key = 72
0 1 2 3 4
a 76 67 72 81 49 linearSearch linearSearch
a = {76, 67, 72, 81, 49} a = {76, 67, 72, 81, 49}
l =1 l =1
r =4 r =4
❶ Initial Call key = 72 key = 72

linearSearch linearSearch linearSearch


a = {76, 67, 72, 81, 49} a = {76, 67, 72, 81, 49} a = {76, 67, 72, 81, 49}
l =0 l =0 l =0
r =4 r =4 r =4
key = 72 key = 72 key = 72

Stack Stack Stack


Testing our code
01 int main() { `
02 int a[] = {31, 67, 59, 43, 71, 48, 54}, key = 71;
03 int pos = linearSearch(a, 0, 6, key);
04

05 if (pos == -1)
06 cout << key << " NOT found" << endl;
07 else
08 cout << key << " found at index " << pos << endl;
09 return 0;
10 }

You might also like