import random
class Search(object):
def binary_search(self, data, value):
"""
二分查找迭代法实现
:param data: list 待查找序列
:param value: int 待查数据
:return: int 索引(查找不到返回-1)
"""
low = 0
high = len(data) - 1
while low <= high:
mid = int((low + high) / 2)
if value < data[mid]:
high = mid - 1
elif value > data[mid]:
low = mid + 1
else:
return mid + 1
return -1
def binary_search_recursion(self, data, low, high, value):
"""
二分查找递归法实现
:param data: list 待查找序列
:param low: int low指针
:param high: int high指针
:param value: int 待查数据
:return: int 索引(查找不到返回-1)
"""
if low <= high:
mid = int((low + high) / 2)
if value < data[mid]:
return self.binary_search_recursion(data, low, mid - 1, value)
elif value > data[mid]:
return self.binary_search_recursion(data, mid + 1, high, value)
else:
return mid + 1
return -1
def main():
search = Search()
data = [0] * 10
for index in range(len(data)):
data[index] = random.randint(1, 10)
data = sorted(data)
print("待查找序列:", data)
res_index = search.binary_search_recursion(data, 0, len(data) - 1, 5)
print("结果索引为:", res_index)
res_index = search.binary_search(data, 5)
print("结果索引为:", res_index)
if __name__ == '__main__':
main()
标签:search,return,int,二分法,查找,low,data
From: https://www.cnblogs.com/lc6666/p/16607755.html