Module 2A Binary Search
Module 2A Binary Search
2
Learning Outcomes
Students will be able to
3
Contents
4
Introduction
5
Divide-and-Conquer Algorithm
5-6
Algorithm Binary-Search
8
Recursive Method
Binary_Search(A[], low, high, x)
// A[]: elements are in ascending order
// low, high: the bounds for searching in A[]
// x: the element to be searched
// If x = A[j], for some j, then return j else return –1
if (low > high) then return –1 // invalid range
if (low = high) then // if small Prob
if (x == ar[i]) then return i
else return -1
else // divide Problem into two smaller sub-problems
mid = (low + high) / 2
if (x == A[mid]) then return mid
else if (x < A[mid]) then
return Binary_Search(A[], low, mid-1, x)
else return Binary_Search(A[], mid+1, high, x)
Example
10
arr = {1, 5, 7, 8, 13, 19, 20, 23, 29}. To Find the item 23
11
Time Complexity
Recurrence Relation for binary search algorithm:
5 - 12
Time Complexity
Let we calculate the time complexity of binary search [4]:
T(n) =
1 + T(n/2) =
1 + (1 + T(n/4)) = 2 + T(n/4) =
2 + (1 + T(n/8)) = 3 + T(n/8) = ...
k + T(n/2k) = ...
log n + T(n/2log n) = log n + T(1) = (*)
log n + 1 = Θ(log n).
13
Test Your Skills…
14
Summary
• Learned binary search which searches in a sorted array by repeatedly
dividing the search interval in half.
• Binary search is an optimal searching algorithm with which we can search
the desired element efficiently.
• The idea of binary search is to use the information that the array is sorted
and reduce the time complexity to O(log2 n).
• Best Case: ɵ(1)
• Average Case: ɵ(log2n)
• Worst Case: ɵ(log2n)
15