1. 程式人生 > >python一個關於二分法查找元素的實現

python一個關於二分法查找元素的實現

oop last 是否 while true return odin utf-8 name

# coding=utf-8
import time


def find_ele(alist, ele):
if ele < alist[0] or ele > alist[len(alist) - 1]:
print("%d not in alist" % ele)
return
last_index = len(alist) - 1
center_index = last_index // 2
loop_flag = True
loop_cout = 0
while loop_flag:
# 使用二分法查找元素是否在有序列表內
loop_cout += 1
while alist[center_index] < ele:
loop_cout += 1
#最後一個元素獲取
center_index = (center_index + last_index + 1) // 2
if center_index == last_index:
# 最後一個元素
if alist[center_index] == ele:
print("%d in alist" % ele)
else:
print("%d not in alist" % ele)
loop_flag = False
break
while alist[center_index] > ele:
loop_cout += 1
last_index = center_index
center_index = last_index // 2
if center_index == last_index:
# 最後一個元素
if alist[center_index] == ele:
print("%d in alist" % ele)
else:
print("%d not in alist" % ele)
loop_flag = False
break
if alist[center_index] == ele:
print("%d in alist" % ele)
loop_flag=False


def main():
print(time.time())
alist = list(range(100000000))
# alist.pop(98)
find_ele(alist, 100)
print (time.time())

if __name__ == "__main__":
main()

python一個關於二分法查找元素的實現