Binary Search (Python)

The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).

input_int_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
input_alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ]
input_words = ["Ajinkya", "Abhijeet", "Abhishek", "Prakash", "Sunil"]

# Function for binary search in a sorted array
def binary_search(input_list_param, element):

    midpoint = len(input_list_param) // 2

    if len(input_list_param) != 0:
        if input_list_param[midpoint] == element:
            return True
            if element < input_list_param[midpoint]:
                return binary_search(input_list_param[:midpoint], element)
                return binary_search(input_list_param[midpoint + 1:], element)
    return False

if __name__ == "__main__":
    print("Found 3: ", binary_search(input_int_list, 3))
    print("Found j: ",binary_search(input_alphabets, 'j'))
    print("Found 'Prakash': ",binary_search(input_words, "Prakash"))


Found 3: True
Found j: True
Found ‘Prakash’: True

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s