Linear Search and Binary Search
Linear Search and Binary Search
2
Continue…
…
Number 281942902 Number 233667136 Number 580625685
Number 701466868 Number 506643548 Number 155778322
3
Linear Search
4
Pseudocode for Linear Search
Algorithm LinearSearch(A,x,n):
Input: Array A of size n, an element x to be searched
Output: Location of searched element.
5
Linear Search Analysis
What are the worst and average case running times for Linear
search?
We must determine the O-notation for the number of
operations required in search.
Number of operations depends on n, the number of entries in
the list.
6
Worst Case Time for Linear Search
7
Average Case for Linear Search
Assumptions:
1. All keys are equally likely in a search
2. We always search for a key that is in the array
Example:
We have an array of 10 records.
If search for the first record, then it requires 1
array access; if the second, then 2 array
accesses. etc.
The average of all these searches is:
(1+2+3+4+5+6+7+8+9+10)/10 = 5.5
8
Average Case Time for Linear Search
9
Binary Search
10
Binary Search Pseudocode
Algorithm BS(A,low,high,x):
Input: Sorted array A of size n, an element x to be searched
Output: Location of searched element.
If (low=high) then
if (A[low]=x) then return(low) else return(-1)
else
mid (low + high) /2
If A[mid] = x then print “ found at mid” Return
else If (A[mid] < x) then BS(A,mid+1,high,x)
else BS(A,low,mid-1,x)
Print “x not found”
Exit 11
Binary Search
3 6 7 11 32 33 53
12
Binary Search
3 6 7 11 32 33 53
13
Binary Search
3 6 7 11 32 33 53
14
Binary Search
3 6 7 11 32 33 53
15
Binary Search
3 6 7 11 32 33 53
16
Binary Search
3 6 7 11 32 33 53
17
Binary Search
3 6 7 11 32 33 53
18
Binary Search
3 6 7 11 32 33 53
19
Binary Search
3 6 7 11 32 33 53
20
Binary Search
3 6 7 11 32 33 53
21
Binary Search
3 6 7 11 32 33 53
23
Binary Search Complexity Analysis:
Substitution Method
1 if n = 1
T(n)=
T(n/2)+C if n>1
T(n) = T(n/2) + c
T(n/2)= T(n/4)+c+c
Put the value of T(n/2) in above so T(n)=T(n/4)+c+c . . . . T(n/2^k)+c+c+c.....+c
=T(n/2^k)+c+c....+c up to k
=T(1)+k.c
As we taken n/2^k = 1
K = log n
So Time complexity is O(log n)
24