Linear and Binary Search
Linear and Binary Search
Data Structure
Searching
• Searching is an operation which finds the
position of a given element in the list.
• The search process is set to be successful or
unsuccessful depending upon the searched
element is found or not.
• Classified into two types:
Linear (sequential) Search
Binary Search
Linear (Sequential) Search
key=8
3 1 7 45 32 8 53
a
Linear (Sequential) Search
key=8
3 1 7 45 32 8 53
Is key==a[0] ? NO
Linear (Sequential) Search
key=8
3 1 7 45 32 8 53
Is key==a[1] ? NO
Linear (Sequential) Search
key=8
3 1 7 45 32 8 53
Is key==a[2] ? NO
Linear (Sequential) Search
key=8
3 1 7 45 32 8 53
Is key==a[3] ? NO
Linear (Sequential) Search
key=8
3 1 7 45 32 8 53
Is key==a[4] ? NO
Linear (Sequential) Search
key=8
3 1 7 45 32 8 53
Linear_search(a[],size,value)
1. for(i=0;i<size;i++)
2. if(value==a[i])
3. return index;
4. return (-1); (Value not found)
end.
Linear (Sequential) Search
• Time Complexity
Best Case
If the searched element is present at the first
place i.e. at a[0], then
T(n)=O(1)
Worst Case
If the searched element is present at the end of
the list i.e. at a[n-1] or it is not present in the list
T(n)=O(n)
Binary Search
3 6 7 11 32 33 53
Binary Search
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
Worst Case
T(n)=O(log2n)
Binary Search
• How T(n)=O(log2n) ?
T(n) = T(n/2) + 1 [1 to find the mid, n/2 for compare with n/2 ele]
-----------(1)
From (1)
T(n/2) = T(n/4) + 1 -----(2)
From (1) and (2)
T(n) = T(n/4) + 2
Again from (1)
T(n/4) = T(n/8) + 1
From the previous equations
T(n) = T(n/8)+3 = T(n/23 ) + 3
----------------------------------------
= T(n/2k) + k -------(3)
After k division only one element left so
n/2k =1 => n = 2k => k=log2n
Now put the value of k into (3)
T(n) = T(1) + log2n = log2n so,
T(n)= O(log2n)
Program-C
• Global Declaration
• main()
• linear_search()
• binary_search()
Thank You