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
重新起航!