Binary Search Binary Search
- Assumes that the data is sorted Steps
- Find median index =
- Then check does (search num) = median num?
- If no, check if (search num) is greater than or less than median num
- Then repeat between l + r
Pseudo Pseudo Logic (PieceWise Description):
BinarySearch(A,x,l,r)
n, r < l
m, A[m] = x
BS(A,x,l, m-1), A[m] > x
BS(A,x,m+1, r), A[m] < x
note: n = null,not in array, m = (current) median
Algorithm Binary Search(A:array, x:item, l:Z, R:Z)
# unsuccessful search
if r < l then:
return n
end if
m <- median formula
# successful search
if A[m] = x then
return m
end if
# split the 'deck'
if A[m] > x then
return BS(A, x, l, m-1);
end if
A[m] < x then
return BS(A, x, m+1, r)
end algorithm
let be the cost of the operations run during the US case
let be the cost of running the successful search case.
We can claim that the cost of going left or right recurse is the same.
Next Step: Runtime Runtime Operations
Runtime for Binary:
we started with n, then , then , then this is
Proof of Binary Search Runtime Proof of Binary Search runtime
How do we prove the respective runtime for this?
-
Induction (mentioned in discrete math)
- Start with an informed guess.
- Basis 0 +
- Induction (n > 1): Assume the statement is true for (Inductive Hypothesis)
Another Method: Substitutions
Iterate until you can determine the form.
= 2Crs + Tss(n/4) = 3Crs +Tss(n/8) = 4Crs + Tss(n/16) … =…
we stop when = 1 → k =
= Crs
Tss(n) = Crs
Therefore we can say that is O()
: c?
c > 0