• 算法-二分查找与排序(冒泡,插入,选择)


    import time
    import random
    
    #装饰器
    def cal_time(func): def wrapper(*args, **kwargs): t1 = time.time() result = func(*args, **kwargs) t2 = time.time() print("%s running time: %s secs." % (func.__name__, t2 - t1)) return result return wrapper
    #二分查找 @cal_time
    def bin_search(data_set, val): low = 0 high = len(data_set) - 1 while low <= high: mid = (low+high)//2 if data_set[mid]== val: return mid elif data_set[mid]< val: low = mid + 1 else: high = mid - 1 return #生成姓名学号年龄一个列表 def random_list(n): result = [] ids = list(range(1001,1001+n)) a1 = ['zhao','qian','sun','li'] a2 = ['li','hao','',''] a3 = ['qiang','guo'] for i in range(n): age = random.randint(18,60) id = ids[i] name = random.choice(a1)+random.choice(a2)+random.choice(a3) data = list(range(100000000)) print(bin_search(data, 173320))

    #冒泡排序
    @cal_time
    def bubble_sort(li):
    for i in range(len(li) - 1):
    for j in range(len(li) - i - 1):
    if li[j] > li[j+1]:
    li[j], li[j+1] = li[j+1], li[j]

    @cal_time
    def bubble_sort_1(li):
    for i in range(len(li) - 1):
    exchange = False
    for j in range(len(li) - i - 1):
    if li[j] > li[j+1]:
    li[j], li[j+1] = li[j+1], li[j]
    exchange = True
    if not exchange:
    break
    #选择排序
    def select_sort(li):
    for i in range(len(li) - 1):
    min_loc = i
    for j in range(i+1,len(li)):
    if li[j] < li[min_loc]:
    min_loc = j
    li[i], li[min_loc] = li[min_loc], li[i]

    #插入排序
    def insert_sort(li):
    for i in range(1, len(li)):
    tmp = li[i]
    j = i - 1
    while j >= 0 and li[j] > tmp:
    li[j+1]=li[j]
    j = j - 1
    li[j + 1] = tmp
     
  • 相关阅读:
    js获取url传递参数
    C#:String.Format数字格式化输出
    mathjs,math.js解决js运算精度问题
    js获取文件后缀
    vue生成二维码插件qrcodejs2
    多行文本超出后隐藏,超出3行隐藏
    vue点击按钮给商品按照价格进行倒叙
    vue关闭代码检查eslint
    vue + elementUi + upLoadIamge组件 上传文件到阿里云oss
    nodejs+expressjs+ws实现了websocket即时通讯,服务器和客户端互相通信
  • 原文地址:https://www.cnblogs.com/niuniu2018/p/8400125.html
Copyright © 2020-2023  润新知