顺序查找
class SSTable:
def __init__(self,b):
self.list=[0]+b
self.length=len(b)
def SeqSearch(self,x):
i=self.length
print(i)
self.list[0]=x
while self.list[i]!=x:
i-=1
return i
b=[1,2,3,4]
a=SSTable(b)
print(a.SeqSearch(2))
折半查找
class SSTable:
def __init__(self,b):
self.list=[0]+b
self.length=len(b)
def binary_search(self, target):
low = 1
high = self.length
mid = 0
while low <= high:
mid = (high + low) // 2
guess = self.list[mid]
if guess == target:
return mid # 找到目标元素,返回其下标
if guess > target:
high = mid - 1
else:
low = mid + 1
return None # 没找到目标元素,返回None
b=[1,2,3,4]
a=SSTable(b)
print(a.binary_search(2))