Binary Search Algorithm in Python

Binary Search has less time complexity as compared to linear search. In linear search, potentially all the members are checked while in binary search case, chunks of data are dropped where the target element is not there according to the conditions in the program.
    
def binarySearch(mylist, target):
    start = 0 # index of 1st element in list
    end = len(mylist)-1 # index of last element in list
    step = 0 # binary search operation step
    
    while start<=end:
        
        if target not in mylist:
            print(f"Sorry the value {target} is not found in the list.")
            return
        
        print("At step:",step,"The list is",mylist[start:end+1])
        step += 1
        
        middle = (start + end) // 2
                
        if target == mylist[middle]:
            print(f"Your target value which is {target} is found in the list at index {middle}")
            return
        elif target < mylist[middle]:
            end = middle - 1
        elif target > mylist[middle]:
            start = middle + 1
            
mylist = [1,2,3,4,5,6,7]
mytarget = 6
binarySearch(mylist, mytarget)
   

    

Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

The Basic Structure of a Full-Stack Web App

Unlocking Web Design: A Guide to Mastering CSS Layout Modes