2. Searching: Finding the location of item or
printing some message when item is not
found.
SEARCH
LINEAR BINARY
3. • Linear search: Traversing data sequentially to
locate item is called linear search.
• Ex: Searching an item for operation in array.
• Binary search: Data in array which is sorted in
increasing numerical order or alphabetically.
• Ex: Searching name in telephone directory,
searching words in dictionary.
4. LINEAR SEARCH
• It test whether the ITEM in DATA is present or
not.
• It test the data in sequential manner.
• It searches the data one by one fully and
returns the ITEM as the result.
• Otherwise, it returns the value 0.
• We see this by ALGORITHM.
6. STEPS:
1. [Insert ITEM at the end] Set DATA[N+1]:=ITEM.
2. [Initialize counter] Set LOC:=1.
3. [Search for ITEM]
Repeat while DATA[LOC]= ITEM:
Set LOC:=LOC+1.
[End if loop]
4. [Successful?]If LOC:=N+1, then ;
Set LOC:=0
5. Exit
8. • To find the item we are first inserting the item
to the end of the list.
• Step 1: DATA[N+1]=ITEM.
Exp:
N=6
DATA[6]=F
DATA[6+1]=G
• So the item is added at LOC[7]
A B C D E F G
1 2 3 4 5 6 7
9. • Step 2:
Initializing the counter to start the search.
Therefore, LOC=1.
It starts the search from LOC=1{i.e. from
DATA[1]=A}
• Step 3:
WHILE loop is executed till DATA[LOC]=ITEM
From the step 2, LOC=1
10. A B C D E F G
A B C D E F G
A B C D E F G
A B C D E F G
S
E
A
R
C
H
I
N
G
DATA[LOC] =ITEM
LOC=LOC+1
DATA[LOC] =ITEM, LOC=LOC+1
DATA[LOC] =ITEM
LOC=LOC+1
LOC=1
LOC=2
LOC=3
11. A B C D E F G
DATA[LOC] =ITEM,
LOC=LOC+1
S
E
A
R
C
H
I
N
G
A B C D E F G
DATA[LOC] =ITEM,
LOC=LOC+1
A B C D E F G
DATA[LOC]
=ITEM,
LOC=LOC+1
LOC=4
LOC=5
LOC=6
12. Here the item is found
The item ‘G’ is located
So the loop executes until this condition
A B C D E F G
DATA[LOC] =ITEM
LOC=7
13. • STEP 4:
Originally the location is 6. We added the
item at the end.
So the item is located in 7.
LOC=N+1
We reached the condition then
LOC=0
• STEP 5:
Searching is finished and the algorithm exits.
14. COMPLEXITY
• Worst Case: The maximum value to search.
• Complexity is measured by f(n).f(n)=n+1
• The average case is measured by probability.
• Here,
• pk – probability that ITEM appears in DATA[K].
• q – probability that ITEM does not appears in
DATA[K].
• Algorithm uses k comparisons when ITEM
appears in DATA[K].
15. • f(n)=1 . p1 + 2 . p2 + … +n . pn + (n+1) . q
• Suppose, q is very small and ITEm appears in
equal probability, then
q=o and pi=1/n
f(n)=1 . 1/n + 2 . 1/n + … +n . 1/n + (n+1).0
=(1+2+…+n) .1/n
=n(n+1)/2.(1/n)
f(n)=(n+1)/2