diff --git a/projects/bsearch/Winners b/projects/bsearch/Winners index f58e252..9f7db44 100644 --- a/projects/bsearch/Winners +++ b/projects/bsearch/Winners @@ -49,3 +49,59 @@ def bsearch(List,item):#defines the function for binary search of an item in a l bottom=mid+1 #assigns the index of the element succeeding the mid to bottom else: return -1 #returns -1 if the search item is not found + + + +# Tewodros Bejiga @02618567 + +def bsearch(list,target): + low = 0 # low is the first index of the list + high = len(list) -1 # high is the highest index in the list which is one less than the lenght of the list. + while low <= high: + mid =(low + high)/2 # mid is the middle element of the list + if target == list[mid]: # In binary search the first element in the list we check to compare with the element we looking for is the middle element + return mid # if the target element is exactlly equal to the middle element then the code will return the index of the element. + elif target < list[mid]: # But in a situation when the target element is less than the middle element then we will search the target in the lower half of the list. + high = mid - 1 + elif target > list[mid]: # when the target element is greater than the middle element then we will search the element in the upper half of the list. + low = mid + 1 + else: + return -1 # Or if the target element is not in the list the code will return -1 in response to that + + + + +def bsearch(pList,pFind): #the function's arguments are a list and an element to be found + + pList.sort() #first the list is sorted using the list class method sort() + + low=0 #the minimum value of the search range is initialied at 0 + high=len(pList)-1 #and the max value is initialized at the last position in the list + + while(low<=high): #the search will run up to and including a range of 1 element. + #If the search element is not in the list at all then the max and + #min value will be equal to the mean position and either the max or min + #value will be assigned the position preceeding or suceeding the mean, respectively, + #and the condition (low<=high) will be false and the loop will terminate + + mid=(low+high)/2 #at each iteration, the mean position of the range is found + + if(pList[mid]==pFind): #if the search element is equal to the element at the mean position + return mid #then the mean position is returned + + elif(pList[mid]pFind): #the last case handled is if the search element is smaller than the + high=mid-1 #element at the mean position. In this case I reduce the search range by + #assigning the max value the position preceeding the mean position + + return -1 #if the search loop terminates without finding the position of the search + #element then that means the element was not found in the list and -1 is returned + + +