Lecture 1.2_correctness_binary_search
Lecture 1.2_correctness_binary_search
Neelima Gupta
January 4, 2021
1/12
Binary Search
Binary-Search(A[], n, key )
left 1, right n
while left right do
mid (left+right)/2
if (A[mid]=key) then
return mid
end
if (A[mid] < key) then
left mid+1
end
else
right mid-1
end
end
return 0
2/12
Defining the I/O of Binary Search
3/12
4/12
5/12
Proof of correctness: The Loop Invariant
Let r be the maximum number of times the loop starting from line
3 runs. For 1 k r , let fk and lk be the values of first and last
respectively when the control reaches the while statement for the
k th time.
I Loop Invariant: For 1 k r , H(k): when the control
reaches the while statement for the k th time A[i] 6= x for
every i < fk and for every i > lk .
I We will prove the loop invariant by induction.
I Base Case: k = 1. fk = 1 and lk = n. Hence the claim is
vacuously true.
6/12
Inductive Step: Suppose H(k) is true. We will prove that H(k + 1)
is true. In the k th iteration, we have three possibilities:
7/12
I Case 2. x < A[mk ].
8/12
I Case 3. x > A[mk ] .
9/12
Correctness of the algorithm assuming the loop invariant
10/12
Correctness of the algorithm assuming the loop invariant
By loop invariant hypothesis, A[i] 6= x for i < ft and for i > lt . the
claim follows as ft > lt .
11/12
Time Complexity
12/12
Time Complexity
12/12
Time Complexity
12/12
Time Complexity
12/12
Time Complexity
12/12
Time Complexity
12/12
Time Complexity
12/12
Time Complexity
12/12