Blogger Tips and TricksLatest Tips And TricksBlogger Tricks

Program to perfrom Linear and Binary Search in python


"Program to perfrom Linear and Binary Search"
print ("Program to Pefrom Linear and Binary Search")
print ("""Enter Your Choice
        1. Linear Serach
        2. Binary Search
        3. Exit""")
#FUNCTION TO PERFORM LINEAR SERACH OPERTAION
def Linear():
    print ("Linear Search")
    E_size=int(input("Enter the Number of Elements : "))
    Llist=[]
    i=1
    flag=0
    for i in range(0,E_size):
        print ("Enter the ", i ," item   ")
        E_item=int(input("The Value : "))
        Llist.append(E_item)
    print (Llist)
    val=int(input("Enter the value to search :"))
    for L_search in Llist:
        if val == L_search:
            flag=1
        else:
            flag=0
    if flag==0 :
        print ("The Element is not found")
    else:
        print ("The Element is found", L_search)
       
#FUNCTION TO PERFORM BINARY SEARCH OPERATION
def Binary():
    print ("Binary Search")
    B_size=int(input("Enter the Number of Elements : "))
    Blist=[]
    i=1
    flag=0
    first=0
    for i in range(0,B_size):
        print ("Enter the ", i ," item   ")
        B_item=int(input("The Value : "))
        Blist.append(B_item)
    last=len(Blist)
    print (Blist)
    val=int(input("Enter the value to search :"))
    while first <= last and flag == 0:
        index=(first+last)//2
        if Blist[index]== val:
            flag=1
        else:
            if val < Blist[index]:
                last=index-1
            else:
                first=index+1
    if flag==1:
         print ("The Element is found", Blist[index])
    else:
        print ("The Element is not found")

def close():
    quit()

option = {1: Linear,
          2: Binary,
          3: close,}
#MAIN FUNCTION
def main():
    op=int(input("Choice Value: "))
    option[op]()
t=1

while t==1:
    main ()

No comments:

Post a Comment

Flag Counter