Module 1-Binary Search
Module 1-Binary Search
• If a list is already sorted, then the search for an end is in the list can be made faster
using divide & conquer technique.
• This is an efficient searching method.
• In this method, the list is divided into two halves separated by middle element.
• An element which is to be searched from the list of elements stored in an array
A[0.......n-1] is called the key element.
❖ Let A[mid] be the middle element of array A, then there are 3 conditions that needs to be
tested while searching the array using this method.
• This search is called binary, because in each iteration, the given list is divided into 2
parts.
• In the next iteration search becomes limited to half the size of list to be searched.
• For instance, in first iteration, size of list is n, which reduces to almost n/2 in second
iteration and so on.
Algorithm[non-recursive]
• Let A be a sorted array of elements with lower bound, lb and upper bound ub
• Let mid represents middle location
• This algorithm searches for an element, ie. key in an array A
lb=0
ub=n-1
while lb<=ub do
mid= int[(lb+ub)/2]
if key=A[mid] then
return mid
elseif key<A[mid] then
ub=mid-1
else
lb=mid+1
end do
If there are 32 elements in an array, we can visualize the worst case scenario as follows:
k=log2n
if(LB>UB)
Return -1
else
mid=int[(LB+UB)/2]
if(key==A[mid])
return mid
elseif(key<A[mid])
BinarySearch(A[],key,LB,mid-1)
else
BinarySearch(A[],key,mid+1,UB)
Analysis
T(n) = T(n/2) + b
= T(n/4) + b + b
= T(n/4) + 2b
= T(n/8) + b +2b
= T(n/8) + 3b
= T(n/16) + b +3b
= T(n/16) + 4b
= T(n/2k) + kb
Given T(1)=1
at 2k = n; k= logn
=T(1) +logn b
=1 +logn b
=O(logn)
3 4 5 7 11 13 14 17 21
0 1 2 3 4 5 6 7 8
• Suppose we desired to search the array A for a value, say 14 and its position in it.
• Binary search begins by looking at middle value in the array.
• The middle index of the array is approximated by averaging the first and last indices
and truncating the results (mid=int [(lb+ub)/2])
ie int[(0+8)/2] = 4
13 14 17 21
5 6 7 8
• It may be noted that the desired element has been found only in 2 steps. Thus, it is a
much faster method as compared to linear search.
The time and space complexity of Binary Search in the best, average, and worst cases.
1. Time Complexity:
➢ Best case complexity: When the element to be searched is found in the first comparison,
i.e. when the searched element is the first middle element, then it is the best case
occurrence. Thus, in the binary search, the best case time complexity is O(1).
➢ Average Case Complexity: In the binary search, the average case of time complexity is
O(logn).
➢ Worst-case complexity: We need to reduce the search space till it has only a single
element. Thus, the worst case in time complexity is O(logn)
2. Space Complexity: