Dear experts in Python,
I have written a binary search method that receives a list of float and one new float item. It needs to look for the proper index for that item to be placed and return that index. To make it simple, I give an example:
imagine a list that is empty at first () is given to this binary search as well as a new value, say 110.2
Now the function should return 0. Cause there is no item there. so my list now is [110.2].
Now if the method is called and the list is passed to it with new value of 112.3, it should return me index of 1 ---> so list is : [110.2, 112.3].
My method works fine with it, but when I finish inserting, last value in the list is always out of sort, like [110.2, 112.3, 121.4, 154.7, 113.6]
Here is the code:
def _Binary_Search_Get_Index (list, newValue): ''' Uses binary search to get the proper index to place item Returns index, if not found, returns -1''' min = 0; max = len(list) - 1 while 1: if max < min: return m m = (min + max) / 2 if list[m] < newValue: min = m + 1 elif list[m] > newValue: max = m - 1 else: return m