二分查找(Binary Search)是一种在有序数组中查找某一特定元素的搜索算法。
它的原理非常简单:首先,将数组从中间分成两半,然后将要查找的数字与数组的中间数字进行比较。如果要查找的数字比中间数字大,那么就在数组的右半部分继续查找,如果要查找的数字比中间数字小,那么就在数组的左半部分继续查找。重复以上过程,直到找到要查找的数字,或者整个数组遍历完毕都没有找到。
下面是一个 Python 代码实现的例子:
def binary_search(arr, x):
low =0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
x = 5
result = binary_search(arr, x)
if result != -1:
print(f"Element is present at index {result}")
else:
print("Element is not present in array")