在本文中,我们将学习解决给定问题陈述的解决方案和方法。
问题陈述-我们将得到一个排序列表,我们需要在二进制搜索的帮助下找到一个元素。
将x与中间元素进行比较。
如果x与中间元素匹配,则返回中间索引。
否则,如果x大于mid元素,则x只能位于mid元素之后的右半子数组中。因此,我们重复右半部分。
否则(x较小)再次出现在左半部分
def binarySearchAppr (arr, start, end, x): # check condition if end >= start: mid = start + (end- start)//2 # If element is present at the middle if arr[mid] == x: return mid # If element is smaller than mid elif arr[mid] > x: return binarySearchAppr(arr, start, mid-1, x) # Else the element greator than mid else: return binarySearchAppr(arr, mid+1, end, x) else: # Element is not found in the array return -1 arr = sorted(['t','u','t','o','r','i','a','l']) x ='r' result = binarySearchAppr(arr, 0, len(arr)-1, x) if result != -1: print ("Element is present at index "+str(result)) else: print ("Element is not present in array")
def binarySearchAppr (arr, start, end, x): # check condition if end >= start: mid = start + (end- start)//2 # If element is present at the middle if arr[mid] == x: return mid # If element is smaller than mid elif arr[mid] > x: return binarySearchAppr(arr, start, mid-1, x) # Else the element greator than mid else: return binarySearchAppr(arr, mid+1, end, x) else: # Element is not found in the array return -1 arr = sorted(['t','u','t','o','r','i','a','l']) x ='r' result = binarySearchAppr(arr, 0, len(arr)-1, x) if result != -1: print ("Element is present at index "+str(result)) else: print ("Element is not present in array")
Element is present at index 4
在本文中,我们了解了应用二进制搜索的方法。