You are on page 1of 13

1

Searching an element in
the list
Linear binary
search search
2

Linear search:
Comparing each element of list with the element which we want
to search or
passing through each element of the list
3

Write a
4

Binary search
This search algorithm works on the principle of divide and conquer.

Binary search looks for a particular item by comparing the


middle most item of the collection. If a match occurs, then the
index of item is returned. 
If the middle item is greater than the item, then the item is searched
in the sub-array to the left of the middle item
Otherwise, the item is searched for in the sub-array to the right
of the middle item.
This process continues on the sub-array as well until the size of
the subarray reduces to zero.
5

Condition in binary
search
Array must be sorted
6

li=[14 ,
18,19,24,34,43,54,56,78,78]
Let the element to search is x=18:

14 18 19 24 34 43 54 56 78 78

lb=0 Find middle position and check if the ub=len(li)-1


element to search x is present at middle
position=(ub+lb)//2 =9//2=4, if yes then
return this position
if x==li[m] :
return x
7

14 18 19 24 34 43 54 56 78 78

X<>li[m] , so find x in first half of list

14 18 19 24 34 43 54 56 78 78

If x<> li[m] , If x<> li[m] ,


Check if x<li[m] Check if x >li[m]
Find x in first half of list Find x in second half of
list
8
Since , x=18 and it is less than li[m] , so will search it in first half of list.

14 18 19 24 34 43 54 56 78 78

Now if x< li[m]


lb= 0 and ub= m-1 =4, (lb not changing ) Now if x>li[m]
find mid again m=(ub+lb )//2 lb= m+1=5 and ub= len(li)-1=9 , (ub
Check if x==li[m] not changing)
Return m find mid again
m=(ub+lb)//2=(9+6)//2=15//2=7
Check if x==li[m]
Return m
Compare x with middle element li[m] i.e
(0+4)//2=2 i.e. li[2]=19
Now again x<> li[m]
9

14 18 19 24 34 43 54 56 78 78

X<> 19 , so check if x< 19 or x>19

14 18 19 24 34 43 54 56 78 78

Again check if x< 19 ,


else if x> 19 , lb=m+1
lb=0 and ub=m-1=1
=3 and no change in
And find middle again
ub=4
as m= (ub+lb)//2 = 0
And find middle again
as m= (ub+lb)//2=
(4+3)//2=7//2=3
10

14 18 19 24 34 43 54 56 78 78

Here , lb=0 , ub=1 so mid= (ub+lb)//2=0


Check if li[m] i.e li[0]==18
Icheck If x<li[m] : element not found in list
Else check
If x>li[m]i.e. x>li[0]
i.e. x>18

Lb=m+1=0+1=1
Ub=1 (no change)
So , m=(lb+ub)//2= (1+1)//2=1

14 18 19 24 34 43 54 56 78 78

Checl if x= =li[m]
return m
11

search
the list 12

[12,13,17,15,29,20,23]
1. USING LINEAR
SEARCH
2.USINg BINARY
SEARCH
13

THANK YOU

You might also like