banner ad

Binary search using python

| January 25, 2013 | 0 Comments
0 Flares 0 Flares ×

A binary search algorithm finds the position of a specified value within a sorted array. In each step, the algorithm compares the value with the key value of the middle element of the array. If the keys match, then a matching element has been found so its index, or returned. Otherwise, if the sought key is less than the middle element’s key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special “Not found” indication is returned. A binary search halves the number of items to check with each iteration, so locating an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.
Concerning the actual code, you should satisfy yourself that it really does terminate correctly. The tricky parts are the conditionBinary Search searches by exploiting the ordering in a sequence in splitting it in half each time.A real-life example of Binary Search would be if you were to look for the name “Larry” in a phonebook, you would first go to the middle of the phonebook, if “Larry” is before the middle entry, you rip and throw away the latter half, and then do the same thing.
Binary Search is an example of divide and conquer paradigm. It runs in O(logn) time on an array of length n.
low <= high
and the assignment
mid = (low + high) / 2.
binary search using python code

def search2(a,m):
    low = 0
    high = len(a) - 1
    while(low <= high):
        mid = (low + high)/2
        midval = a[mid]

        if midval < m:
            low = mid + 1
        elif midval > m:
            high = mid - 1
        else:
            print mid
            return mid
    print -1
    return -1

if __name__ == "__main__":
    a = [int(i) for i in list(sys.argv[1])]
    m = int(sys.argv[2])
    search2(a,m)
Download PDF
0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Reddit 0 StumbleUpon 0 0 Flares ×

Tags: ,

Category: Function

About the Author ()

My name is John Link.I am 26 years old. My major is Computer science and technology. I am a junior programmer with Python.

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Reddit 0 StumbleUpon 0 0 Flares ×