二进制python
Binary Search: Binary search is a searching algorithm which is used to search a number in a sorted array or list.
二进制搜索 :二进制搜索是一种搜索算法,用于搜索排序后的数组或列表中的数字。
Description:
描述:
Binary search uses Decrease and Conquer Algorithm. In this algorithm original problem is decreased by a constant factor and a sub-problem is created and then the sub-problem is further solved to get the solution of the original problem. This process keeps on going unless the problem is solved or no further division is possible.
二进制搜索使用减少和征服算法 。 该算法将原始问题减少一个常数因子,并创建一个子问题,然后进一步解决该子问题以获得原始问题的解决方案。 除非问题解决或无法进行进一步划分,否则此过程将继续进行。
Procedure for Binary Search:
二进制搜索的步骤:
First sort the array (ascending or descending totally depends upon user)
Start = 0, end = length (array) – 1
Mid = (start + end) / 2
While start is less than end
If array[mid] == number
Print number found and exit
If array[mid] > number
End = mid – 1
Mid = (start + end) / 2
If array[mid] < number
Start = mid + 1
Mid = (start + end) / 2
End of while
Time Complexity : O(logn)
时间复杂度:O(logn)
Note: For binary search array or list needs to be sorted before searching otherwise one may not get correct result.
注意:对于二进制搜索数组或列表,需要在搜索之前进行排序,否则可能无法获得正确的结果。
用于二进制搜索的Python代码 (Python code for binary search)
def binary_search(l, num_find):
'''
This function is used to search any number.
Whether the given number is present in the
list or not. If the number is present in list
the list it will return TRUE and FALSE otherwise.
'''
start = 0
end = len(l) - 1
mid = (start + end) // 2
# We took found as False that is, initially
# we are considering that the given number
# is not present in the list unless proven
found = False
position = -1
while start <= end:
if l[mid] == num_find:
found = True
position = mid
break
if num_find > l[mid]:
start = mid + 1
mid = (start + end) // 2
else:
end = mid - 1
mid = (start + end) // 2
return (found, position)
# Time Complexity : O(logn)
# main code
if __name__=='__main__':
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
num = 6
found = binary_search(l, num)
if found[0]:
print('Number %d found at position %d'%(num, found[1]+1))
else:
print('Number %d not found'%num)
Output
输出量
Number 6 found at position 7
翻译自: https://www.includehelp.com/python/binary-search-program.aspx
二进制python