Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Binary search of ordered lists with multiple identical values
- sorted_list=[1, 2, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 9]
- print( "Length of sorted list is " ,len(sorted_list))
- print("Sorted List: ", sorted_list)
- def binary_search(sorted_list, value):
- left = 0
- right = len(sorted_list) - 1
- while left <= right:
- mid = int((left + right)/2) # mid = (left+right)//2
- if sorted_list[mid] > value:
- right = mid - 1
- elif sorted_list[mid] < value:
- left = mid + 1
- elif sorted_list[mid] == value:
- leftmid = mid
- while sorted_list[leftmid-1] == value:
- leftmid = leftmid-1
- rightmid = mid
- while sorted_list[rightmid+1] == value:
- rightmid = rightmid+1
- return leftmid , rightmid
- return False
- value = 4 #can change the search value here
- temp = binary_search(sorted_list, value )
- if temp != False:
- print("Value > ", value)
- print("left index is " + str(temp[0]))
- print("right index is " + str(temp[1]))
- else:
- print("Value > ", value)
- print(temp)
- '''
- Sample output:
- Length of sorted list is 13
- Sorted List: [1, 2, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 9]
- Value > 4
- left index is 3
- right index is 7
- '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement