一.查找算法:
1.
顺序查找:
普通程序:
def sequefind(l,x):
k=0
while k<=len(l)-1 and x!=l[k]:
k=k+1
if k>len(l)-1:
return 0
else:
return k
s=[2,6,7,3,9,98]
while(1):
key=int(input("
待查找的数是
:"))
n=sequefind(s,key)
if n==0:
print("
未找到
")
else:
print(key,"
是第
",n,"
个元素
")
改进程序:
def improveseque(l,x):
l[0]=x
k=len(l)-1
while x!=l[k]:
k=k-1
return k
l=[-1,10,11,90,3,32,5,6,18,15,19,35,9,22,91,88,98]
while(1):
key=int(input("
待查找的数是
:"))
n=improveseque(l,key)
if n==0:
print("
未找到
")
else:
print(key,"
是第
",n,"
个元素
")
2.
二分查找:
def halffind(arr,x):
l=0
h=len(arr)-1
while l<=h:
m=(l+h)//2
if arr[m]==x:
return m
else:
if x