zoukankan      html  css  js  c++  java
  • 算法-二分查找与排序(冒泡,插入,选择)

    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
     
  • 相关阅读:
    F# 语法概览
    Excel 帮助无法正常工作的解决方法
    autofac 组件的实例范围
    visual studio code 中隐藏从 ts 文件生成的 js 文件和 map 文件
    git vim 编辑器基本操作
    nhibernate 中 lazy="no-proxy" 时的问题
    什么是数据科学
    Elasticsearch 疑难解惑
    Hadoop MapReduce执行过程实例分析
    深入浅出JVM
  • 原文地址:https://www.cnblogs.com/niuniu2018/p/8400125.html
Copyright © 2011-2022 走看看