Binary and Linear search(PYTHON)

 def binary_search(size, list1, z):
    list1.sort()
    low = 0
    high = size-1
    index = -1
    while(low <= high):
        mid = (low+high)//2
        if list1[mid] < z:
            low = mid+1
        elif list1[mid] > z:
            high = mid-1
        elif list1[mid] == z:
            index = mid
            print("found at index: ", mid)
            break
    if index == -1:
        print("Not found")


def linear_search(size, list1, z):
    index = -1
    for i in range(size):
        if list1[i] == z:
            index = i
            print("found at index :", i)
            break
    if index == -1:
        print("Not found")


print("enter the size of list : ")
n = int(input())
l = [int(input("enter the elements")) for i in range(n)]
print("enter the element to be searched :")
z = int(input())
binary_search(n, l, z)
linear_search(n, l, z)

Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree