冒泡:
import randomdef _sort(_lst): count = 1 while count < len(_lst): for i in range(0, len(_lst)-1): if _lst[i] >= _lst[i+1]: tem = _lst[i+1] _lst[i+1] = _lst[i] _lst[i] = tem count += 1 return _lstif __name__ == "__main__": __lst = [] for j in range(1, 80): __lst.append(random.randint(1, 111)) print("origin: %s" % __lst) print("sorted: %s" % _sort(__lst))
二分查找(判断元素是否存在):
def search(lst, des): if len(lst) == 0: return False else: while True: start = 0 end = len(lst) // 2 for ix in range(start, end+1): if lst[ix] == des: return True lst = lst[end:]if __name__ == "__main__": __lst = [1, 2, 6] print(search(__lst, 6))
二分查找(返回index,附带测试代码):
import randomdef search(lst, des): length = len(lst) start = 0 end = length//2 if length == 0: return False else: while True: for ix in range(start, end+1): try: if lst[ix] == des: return ix except IndexError: print(ix) if start == end: break start = end end = end + (length+end)//2 # 这种赋值有问题,这段代码有个偶现的bug,可能和这里有关 if end >= length-1: return Falseif __name__ == "__main__": for j in range(0, 200): __lst = [] for i in range(1, 101): __lst.append(random.randint(1, 20)) # print(__lst) index = search(__lst, 6) if index: if __lst[index] != 6: print(search(__lst, 6)) print("False")