📜  Python的二进制搜索(二分法)

📅  最后修改于: 2021-05-05 00:39:52             🧑  作者: Mango

二进制搜索是一种用于搜索排序列表中元素的技术。在本文中,我们将研究执行二进制搜索的库函数。

查找元素的首次出现。

# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
  
def BinarySearch(a, x):
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    else:
        return -1
  
a  = [1, 2, 4, 4, 8]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
    print(x, "is absent")
else:
    print("First occurrence of", x, "is present at", res)
输出:
First occurrence of 4 is present at 2

寻找小于x的最大值。

# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
  
def BinarySearch(a, x):
    i = bisect_left(a, x)
    if i:
        return (i-1)
    else:
        return -1
  
# Driver code
a  = [1, 2, 4, 4, 8]
x = int(7)
res = BinarySearch(a, x)
if res == -1:
    print("No value smaller than ", x)
else:
    print("Largest value smaller than ", x, " is at index ", res)
输出:
Largest value smaller than  7  is at index  3

寻找最右边的事

# Python code to demonstrate working
# of binary search in library
from bisect import bisect_right
  
def BinarySearch(a, x):
    i = bisect_right(a, x)
    if i != len(a)+1 and a[i-1] == x:
        return (i-1)
    else:
        return -1
  
a  = [1, 2, 4, 4]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
    print(x, "is absent")
else:
    print("Last occurrence of", x, "is present at", res)
输出:
Last occurrence of 4 is present at 3

请参考二进制搜索以编写自己的二进制搜索代码。

参考 :
https:// docs。 Python.org / 3 / library / bisect.html