Searching (Binary and Linear)
Searching (Binary and Linear)
PROBLEM: SEARCH
We are given a list of records.
Each record has an associated key.
…
Number 281942902 Number 233667136 Number 580625685
Number 701466868 Number 506643548 Number 155778322
i=0
Yes No
K = A[i]?
i = i+1
No
Print "Successful" i≥n
Yes
Print "Unsuccessful"
Stop
PSEUDOCODE FOR SERIAL 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
AVERAGE CASE TIME FOR SERIAL SEARCH
Generalize for array size n.
mid = (l+u)/2
YES NO
K = A[mid]?
YES NO
K < A[mid]?
Search is successful
u = mid-1 l = mid+1
Stop
NO
(l>u)?
YES
Search is unsuccessful
Start
BINARY SEARCH PSEUDOCODE
…
if(size == 0)
found = false;
else {
middle = index of approximate midpoint of array segment;
if(target == a[middle])
target has been found!
else if(target < a[middle])
search for target in area before midpoint;
else
search for target in area after midpoint;
}
…
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
11
6 33
3 7 32 53
SEARCH FOR TARGET = 7
Find midpoint:
3 6 7 11 32 33 53
Start at root:
11
6 33
3 7 32 53
SEARCH FOR TARGET = 7
Search left subarray:
3 6 7 11 32 33 53
3 7 32 53
SEARCH FOR TARGET = 7
Find approximate midpoint of subarray:
3 6 7 11 32 33 53
3 7 32 53
SEARCH FOR TARGET = 7
Search right subarray:
3 6 7 11 32 33 53
3 7 32 53
BINARY SEARCH: ANALYSIS
Worst case complexity?
What is the maximum depth of recursive calls in binary
search as function of n?
Each level in the recursion, we split the array in half
(divide by two).
Therefore maximum recursion depth is floor(log n) and
2
worst case = O(log2n).
Average case is also = O(log n).
2
CAN WE DO BETTER THAN O(LOG 2N)?