计算时间的迭代器
import time 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
冒泡排序
#coding=utf-8 from cal_time import cal_time @cal_time def bubble_sort(li): for i in range(0,len(li)-1): exchange=False for j in range(0,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 @cal_time def bubble_sort2(li): #i表示第i趟,延续区有i个数 for i in range(len(li)-1,0,-1): for j in range(len(li)-1-i,0,-1): if li[j-1] < li[j]: li[j - 1], li[j]=li[j],li[j-1] import random li =list(range(10000)) random.shuffle(li) # bubble_sort2(li) bubble_sort(li) print(li)
选择排序
from cal_time import cal_time @cal_time def select_sort(li): #第i趟,有序列li[0:i],无序列li[i,n] for i in range(len(li)-1): min_loc=i for j in range(i+1,len(li)): if li[min_loc]>li[j]: min_loc=j li[i],li[min_loc]=li[min_loc],li[i] import random li=list(range(10000)) random.shuffle(li) select_sort(li) print(li)
插入排序
def insert_sort(li): for i in range(1,len(li)): #i表示趟数,也表示摸到牌的下标 j=i-1 tmp=li[i] while j>=0 and li[j]>tmp: li[j+1]=li[j] j-=1 li[j+1]=tmp import random li =list(range(10000)) random.shuffle(li) insert_sort(li) print(li)
快速排序
from cal_time import cal_time def partition(li,left,right): i=random.randint(left,right) li[i],li[left]=li[left],li[i] tmp=li[left] while left<right: #从右边找到比tmp小的数 while left<right and li[right]>=tmp: right-=1 li[left]=li[right] #从左边找比temp大的数 while left<right and li[left]<=tmp: left+=1 li[right]=li[left] li[left]=tmp return left def _quick_sort(li,left,right): if left<right: mid=partition(li,left,right) _quick_sort(li,left,mid-1) _quick_sort(li,mid+1,right) @cal_time def quick_sort(li): return _quick_sort(li,0,len(li)-1) import random li=list(range(10000)) random.shuffle(li) quick_sort(li) print(li)
堆排序
from cal_time import cal_time def sift(data, low, high): i = low j = 2 * i + 1 tmp = data[i] while j <= high: #孩子在堆里 if j + 1 <= high and data[j] < data[j+1]: #如果有右孩子且比左孩子大 j += 1 #j指向右孩子 if data[j] > tmp: #孩子比最高领导大 data[i] = data[j] #孩子填到父亲的空位上 i = j #孩子成为新父亲 j = 2 * i +1 #新孩子 else: break data[i] = tmp #最高领导放到父亲位置 @cal_time def heap_sort(data): n = len(data) for i in range(n // 2 - 1, -1, -1): sift(data, i, n - 1) #堆建好了 #挨个换数 for i in range(n-1, -1, -1): data[0], data[i] = data[i], data[0] sift(data, 0, i - 1) li=list(range(10000)) import random random.shuffle(li) heap_sort(li) print(li)
归并排序
def merge(li, low, mid, high): i = low j = mid + 1 ltmp = [] while i <= mid and j <= high: if li[i] <= li[j]: ltmp.append(li[i]) i += 1 else: ltmp.append(li[j]) j += 1 while i <= mid: ltmp.append(li[i]) i += 1 while j <= high: ltmp.append(li[j]) j += 1 li[low:high + 1] = ltmp def mergesort(li, low, high): if low < high: mid = (low + high) // 2 mergesort(li, low, mid) mergesort(li, mid + 1, high) merge(li, low, mid, high) li=[2,5,7,8,9,1,3,4,6] mergesort(li,0,len(li)-1) print(li)
直接插入排序最好时间复杂度为O(n)