Pages

Thursday, 25 February 2016

Binary Search In Python

# Write A Program For Binary Search In Linear List….
# Set your Font type as Courier

def bsearch(L,z) :
    M=list(L)
    f=0
    l=len(L)
    for i in range(len(L)) :
        mid=(f+l)/2
        if L[mid]==z :
            return mid+1
        elif L[mid]!=z :
            if L[mid]>z :
                l=mid-1
            elif L[mid]<z :
                f=mid+1
    return 0
n=int(raw_input("Enter the length of list"))
L=[0]*n
for i in range(n) :
    L[i]=int(raw_input("Enter Element"+str(i+1)+" : "))
L.sort()
z=int(raw_input("Enter item to be searched for : "))
p=bsearch(L,z)
if p==0 :
    print"Not found"
else :
    print "Element Found at Position",p