Sunday, 25 November 2012

Connecting bits together to form pieces

So, after a good hour of reading (also included the trip to subway to get a sandwich) through the lecture slides and the course notes, I understand what the question is asking and I arrived at a probable solution. So, far it seems to be correct but I can't be totally sure until I write a proof to backup my algorithm.

Here's the code:
    binSearch(x, A):
        b = 0
        e = length(A) - 1  # e = n - 1
        while b <= e:
            m = (b+e) // 2
            if A[m] >= x:
                e = m - 1
            else:
                b = m + 1
        if A[b] == x:
            return b
        else:
            return -1

I've traced the code using a few examples and it seems to work (also the code is almost exactly the same as the lecture slides, just minor changes). But that isn't enough to prove correctness, and now I'm going to try to come up with a proof. And when I do come up with a proof , I'll post how I went about it.

No comments:

Post a Comment