Run Code  | Code Wall  | Users  | Misc  | Feedback  | About  | Login  | Theme  | Privacy 

binary_search_in_python

      
            
                
            
 run  | edit  | history  | help 0

def binary_search(list,term):

    #print(len(list))
        if len(list) == 0:
            return "Not found"

        mid = int(list.__len__()/2)

        if(list[mid] == term):

            return list[mid] 



        if(term > list[mid]):

               last = -1 if mid == 1 else len(list)

               return binary_search(list[mid:last],term)
        else:

                return binary_search(list[0:mid],term)

def binary_search_while(list,term):

    while len(list) != 0:
        mid = int(len(list)/2)

        if list[mid] == term:
            return list[mid]

        if(term > list[mid]):
            last = -1 if mid == 1 else len(list)
            list = list[mid:last]
        else:
            list = list[0:mid]  

    return "not found"        

list = [1,2,3,4,5,6,7,8]

print(binary_search_while(list,9))

  by  psrpsrpsrpsr, 1 years ago




Please log in to post a comment.
gj