排序法
二分法
# 递归 lst = [2, 3, 5, 10, 15, 16, 18, 22, 26, 30, 32, 35, 41, 42, 43, 55, 56, 66, 67, 69, 72, 76, 82, 83, 88] def func(num, left, right): if left <= right: mid = (right + left) // 2 if lst[mid] > num: right = mid - 1 return func(num, left, right) if lst[mid] < num: left = mid + 1 return func(num, left, right) if lst[mid] == num: print("找到此数字") return mid else: print("列表中没有此数字") return -1 func(69, 0, len(lst)-1) # 循环 left = 0 right = len(lst) - 1 num = int(input("请输入查找的数字:")) while left <= right: mid = (left + right)//2 if lst[mid] < num: left = left + 1 if lst[mid] > num: right = right -1 if lst[mid] == num: print("找到此数字") break else: print("列表中没有次数字")
冒泡排序法
lst = [666, 555, 444, 333, 2, 1] n = 0 # 用于比较是否完成(len(lst)-1)!此交换 m = 1 # 用于每轮比较都比上上轮少一次 sum = 0 # 比较循环的总数 l = 1 # 计算循环的总数 k = 0 # k 与 k+1 位置的比较交换 while l < len(lst): # sum为需要交换的最多次数=(len(lst)-1)! sum = sum + l l += 1 while n < sum: while k < len(lst) - m: # 第一轮需要比较len(lst)-1次,下一轮需要比较len(lst)-2次.以此类推 if lst[k] > lst[k + 1]: lst[k], lst[k + 1] = lst[k + 1], lst[k] k += 1 # 大于交换 k+1 else: k += 1 # 小于或等于不变 k+1 n += 1 # 循环次数加1 m += 1 # 下一轮的比较次数减一次 len(lst) - m k = 0 # k置零从头开始比较冒泡 print(lst)
快排
def quicksort(list): if len(list) < 2: return list else: mid_num = list[0] large_num = [i for i in list[1:] if i > mid_num] sm_num = [i for i in list[1:] if i <= mid_num] result = quicksort(sm_num) + [mid_num] + quicksort(large_num) return result