I'm having a hard time understanding how induction, coupled with some invariant, can be used to prove the correctness of algorithms. Namely, how is the invariant found, and when is the inductive hypothesis used- particularly for binary search? I haven't been able to find an intuitive response yet, so I was hoping someone could shed some light on the topic here.
Proofs by Induction A proof by induction is just like an ordinary proof in which every step must be justified. However it employs a neat trick which allows you to prove a statement about an arbitrary number n by first proving it is true when n is 1 and then assuming it is true for n=k and showing it is true for n=k+1.
Binary search begins by comparing an element in the middle of the array with the target value. If the target value matches the element, its position in the array is returned. If the target value is less than the element, the search continues in the lower half of the array.
Let's assume that binary search is defined like this:
def binary_search(a,b,e,x):
n = e-b
if n==0: return None
m = b + int(n/2)
if x<a[m]: return binary_search(a,b,m,x)
if x>a[m]: return binary_search(a,m+1,e,x)
return m
Where
The goal of the function is to return i where a[i]==x if there is such a value of i, otherwise return None.
binary_search works for a range of size zero:
Assuming binary_search works for a range of elements of any size from 0 to n, then binary search works for a range of elements of size n+1.
Proof:
Because the array is sorted, if x < a[m], then x < a[k] for all k > m. This means we only need to search the range [b,m). The range [b,m) is necessarily smaller than the range [b,e), and we've assumed that binary search works for all ranges of size smaller than n+1, so it will work for [b,m).
If x > a[m], then similar logic applies.
If x==a[m], then the function will return m, which is correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With