用于二进制搜索的Python程序
在本文中,我们将学习解决给定问题陈述的解决方案和方法。
问题陈述-我们将得到一个排序列表,我们需要在二进制搜索的帮助下找到一个元素。
算法
将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
结论
在本文中,我们了解了应用二进制搜索的方法。
以上是 用于二进制搜索的Python程序 的全部内容, 来源链接: utcz.com/z/340883.html