【Algorithm】查找之“折半查找”
程序员文章站
2024-03-20 19:56:22
...
class Solution():
def search(self,array , key ,begin , n):#进行折半查找
mid = int((begin + n) / 2)
# print(begin,mid,n)
if key == array[mid]:
return mid
if key < array[mid] :
print(key,array[mid],begin,mid,n)
if begin<=mid-1:
return self.search(array, key, begin, mid - 1)
else:
return -1
if key > array[mid] :
if mid+1<=n:
return self.search(array, key, mid + 1, n)
else:
return -1
array=[1,4,5,8,6,3,2]
key=7
begin=0
n=len(array)-1
array.sort()
t=Solution()
print(array)
t=t.search(array,key,begin,n)
print(t)