Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # method for binary search
- def binarySearch(element, myList2):
- # initially values for upper and lower bounds
- low = 0
- high = len(myList) - 1
- # boolean variable to indicate that the element has been found
- found = False
- # loop till high is greater than low or till the element is not found
- while low <= high and found is False:
- # calculate the mid value
- mid = int((low + high)/2)
- # compare the mid value with the element
- # if equal then print the position and return
- if myList2[mid] == element:
- print("Element " + str(element) + " found at position " + str(mid + 1))
- found = True
- break
- # else if the middle value if greater than the element
- # then element lies on the left side of the mid so decrease high value
- elif myList2[mid] > element:
- high = mid - 1
- # else if the middle value if less than the element
- # then element lies on the right side of the mid so increase low value
- elif myList2[mid] < element:
- low = mid + 1
- # display this if element not found
- if found is False:
- print("Element " + str(element) + " not present in the List")
- return
- # main function
- # accepts comma seperated values for the list
- myList = list(map(int, input("Enter the Elements of the List : ").strip().split(',')))
- # binary search requires the list to be sorted to begin searching
- myList.sort()
- print("The sorted List is : ")
- print(myList)
- binarySearch(8, myList)
- binarySearch(232, myList)
- binarySearch(4235, myList)
- binarySearch(7, myList)
- binarySearch(1, myList)
- '''
- Enter the Elements of the List : 12,23,5475,679,790,9232,232,4235,13,1,6
- The sorted List is :
- [1, 6, 12, 13, 23, 232, 679, 790, 4235, 5475, 9232]
- Element 8 not present in the List
- Element 232 found at position 6
- Element 4235 found at position 9
- Element 7 not present in the List
- Element 1 found at position 1
- '''
Add Comment
Please, Sign In to add comment