# coding=utf-8import 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()
原文地址:https://www.cnblogs.com/sssantiago/p/9490298.html
时间: 2024-10-18 12:09:32