Search Here

Python program to implement Linear & Binary Search

# Linear & Binary Search

import random
import math

c = 0 # c is a counter to calculate Runtime complexity
n = 0 # Size of the array
A = [] # 1D Array declaration

def get_size():
    global n
    n = int(input("\nEnter number of elements: "))

def arbitrary_input(): # For Linear Search
    global n
    global A
    for i in range(n):
        A.append(random.randint(1,n))

def sorted_input(): # For Binary Search
    global n
    global A
    for i in range(1 , n):
        A.append(i)

def show():
    global A
    print("\nGiven Values to serach from: ")
    print("\t",A,"\n")

# Linear Search Starts
def lsearch(key):
    global c
    global n
    global A
    flag = 0
    for i in range(n):
        c=c+1
        if A[i] == key:
            print(key , " is found\n")
            flag = 1
            break
        
    if flag == 0:
        print(key , " is not found\n")
# Linear Search Ends

# Binary Search Starts
def bsearch(key):
    global c
    global n
    global A

    flag = 0
    first = 0
    last = n - 1
    while first <= last:
        c=c+1
        mid = int((first+last)/2)
        if A[mid] == key:
            print(key , " is found\n")
            flag = 1
            break
        elif A[mid]>key:
            last = mid-1
        else: first = mid+1
    if flag == 0: print(key , " is not found\n")
# Binary Search Ends


# __________________________ Main Block Starts __________________________
print("\t\t\t____Linear & Binary Search____")
get_size()
key = int(input("\t\tEnter key element to search: "))

print("\t1. Linear Search\t2. Binary Search\n")
ch = int(input("\t\tEnter your choice: "))

if ch == 1:
    arbitrary_input()
    show()
    lsearch(key)# calling linear search
    print("Theoritical Complexity: ",n)
    print("Practical Complexity: ",c)

elif ch == 2:
    sorted_input()
    show()
    bsearch(key) # calling binary search
    print("Theoritical Complexity: ",math.log(n))
    print("Practical Complexity: ",c)

else: print("Invalid Choice")

Linear & Binary Search
Output

No comments:

Post a Comment