(1)确定性查找(线性搜索)
m = list(range(1, 101))
def search(m, n, x):
for i in range(0, n):
if (m[i] == x):
return i
return -1
n = len(m)
x = int(input("请输入要查找的数字:"))
result = search(m, n, x)
if (result == -1):
print("元素不在数组中")
else:
print("元素在数组中")
(2)不确定性搜索
import random
list1 = list(range(1, 101))
def find(list):
x = int(input("输入数字:"))
while 1:
flag = random.randint(0, 1)
step = 1 if flag else -1
x = x + step
if x < 0:
x += 1
if x > len(list):
x -= 1
if (list[x] == x):
print("元素在数组中" )
else:
print("元素不在数组中" )
break
find(list1)