各种排序算法

import sys
sys.setrecursionlimit(1000000) # 设定递归

冒泡排序 (************************)

时间复杂度:O(n^2)

def Bubble_sort(li):
for i in range(len(li)-1):
for j in range(len(li)-1-i):
if li[j] > li[j+1]:
li[j], li[j+1] = li[j+1], li[j]

选择排序

时间复杂度:O(n^2)

def select_sort(li):
for i in range(len(li)):
minLoc = i ###i = 0
for j in range(i+1, len(li)):
if li[j] < li[minLoc]:
li[j], li[minLoc] = li[minLoc], li[j]

插入排序

时间复杂度: O(n^2)

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

def partition(li, left, right):
tmp = li[left]
while left < right:
while left < right and li[right] >= tmp:
right = right - 1
li[left] = li[right]
while left < right and li[left] <= tmp:
left = left + 1
li[right] = li[left]
li[left] = tmp

return left

快速排序

时间复杂度:O(nlogn)

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)

import time,random
li = [random.randint(1,100) for _ in range(100000)]
start = time.time()
quick_sort(li, 0, len(li)-1)
cost = time.time() - start
print('quick_sort:%s' % (cost))

import time,random
li = [random.randint(1,100) for _ in range(100000)]
start = time.time()
Bubble_sort(li)
cost = time.time() - start
print('bubble_sort:%s' % (cost))

import time,random
li = [random.randint(1,100) for _ in range(100000)]
start = time.time()
insert_sort(li)
cost = time.time() - start
print('insert_sort:%s' % (cost))

posted @ 2019-12-26 01:01  沐知  阅读(98)  评论(0编辑  收藏  举报