Ch7-Searching(1 slide per page)
Ch7-Searching(1 slide per page)
Search Algorithms
Learning objectives:
Analysis of two search algorithms
Divide-and-conquer technique
Lecture Plan:
7.1 Sequential Search O(n)
7.2 Binary Search O(log2n)
7.3 Analysis of Binary Search
Searching Problem
The algorithm begins at the first element in the array and looks at each
element in turn until K is found or the end of the array is reached.
ALGORITHM sequentialSearch(A[0..n-1],K)
// Input: an array A[0..n-1] and a search key K
// Output: the index of the element of A that
// matches K, or –1 if there is no such element
i 0
while i n-1 and A[i]K do
i i+1
if i < n return i // i is the index of key K
else return -1 // key K is not found
ALGORITHM sequentialSearch(A[0..n-1],K)
// Input: an array A[0..n-1] and a search key K
// Output: the index of the element of A that
// matches K, or –1 if there is no such element
i 0
while i n-1 and A[i]K do
i i+1
if i < n return i // i is the index of key K
else return -1 // key K is not found
0 5 2 false false
3 5 4 true
The algorithm returns 4, the index of the element of the element which is equal to K.
ALGORITHM binarySearch(A[l..r],K)
while l r do
mid (l+r)/2 Binary Search: Analysis
if K == A[mid] return mid
else
if K < A[mid] r mid-1
else l mid+1
return –1
If we divide an array of n elements in half, then divide one of those halves in half, and
continue dividing halves until only one element remains, we perform no more than q
n
divisions (because q = 1 according to our assumption (1)).
2
Thus in the worst case the algorithm performs no more than q iterations and,
therefore, q comparisons (considering K==A[mid] as the main operation).
Due to (1), q = log2n.
It means that the time complexity of the algorithm is O(logn) in the worst case.
7.3 Analysis of Binary Search