Python program for Binary Search

Binary pursuit in python: Here, we will figure out how to actualize a binary hunt in a cluster or rundown in python.

Binary Search: Binary pursuit is a looking through calculation which is utilized to look through a number in an arranged cluster or rundown.

Depiction:

Binary pursuit utilizes Decrease and Conquer Algorithm. In this calculation unique issue is diminished by a consistent factor and a sub-issue is made and afterwards, the sub-issue is additionally fathomed to get the arrangement of the first issue.

This procedure continues going except if the issue is tackled or no further division is conceivable.

Method for Binary Search:

    First sort the array (ascending or descending totally depends upon user)
    Start = 0, end = length (array) – 1
    Mid = (start + end) / 2
    While start is less than end
        If array[mid] == number
            Print number found and exit
        If array[mid] > number
            End = mid – 1
            Mid = (start + end) / 2
        If array[mid] < number
            Start = mid + 1
            Mid = (start + end) / 2
    End of while

Time Complexity: O(logn)

Note: For binary inquiry exhibit or rundown should be arranged before looking through else one may not get the right outcome.

Python code for binary inquiry:

def binary_search(l, num_find):
    '''
    This function is used to search any number.
    Whether the given number is present in the
    list or not. If the number is present in list
    the list it will return TRUE and FALSE otherwise.
    '''
    start = 0
    end = len(l) - 1
    mid = (start + end) // 2
    
    # We took found as False that is, initially
    # we are considering that the given number
    # is not present in the list unless proven
    found = False
    position = -1

    while start <= end:
        if l[mid] == num_find:
            found = True
            position = mid
            break
        
        if num_find > l[mid]:
            start = mid + 1
            mid = (start + end) // 2
        else:
            end = mid - 1
            mid = (start + end) // 2

    return (found, position)

    # Time Complexity : O(logn)


# main code
if __name__=='__main__':
    
    l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    num = 6
    found = binary_search(l, num)
    if found[0]:
        print('Number %d found at position %d'%(num, found[1]+1))
    else:
        print('Number %d not found'%num)

Output:

Number 6 found at position 7

Leave a Comment

error: Alert: Content is protected!!