Advertisement
zhongnaomi

binary_search_leftmost

Feb 15th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. """
  2. Created on Fri Feb 15 17:26:21 2019
  3.  
  4. @author: Naomi Toshiba
  5. """
  6.  
  7. '''
  8. function binary_search_leftmost(A, n, T):
  9.    L := 0
  10.    R := n
  11.    while L < R:
  12.        m := floor((L + R) / 2)
  13.        if A[m] < T:
  14.            L := m + 1
  15.        else:
  16.            R := m
  17.    return L
  18. '''
  19.  
  20. numberli1=[1, 2, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 9]
  21. number2=4
  22. def binary_search_leftmost(sorted_list,value):
  23.    
  24.    
  25.     move_count=1
  26.     left =0
  27.     right = len(sorted_list)
  28.     while left < right :
  29.         mid = int((left + right)/2)
  30.        
  31.        
  32.         if sorted_list[mid]<value:
  33.             left = mid+1
  34.             move_count +=1
  35.         else:
  36.             right = mid
  37.             move_count +=1
  38.            
  39.        
  40.     return left,move_count
  41.  
  42. pos1,m1=binary_search_leftmost(numberli1,number2)
  43.    
  44. print('The number is the ', str(pos1+1),' number in the list.')
  45. print('binary search leftmost took ' ,str(m1),'times to move')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement