冒泡
def bubble_sort(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:
return
插入
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 -= 1
li[j+1] = tmp
return li
选择
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
if min_loc != i:
li[i], li[min_loc] = li[min_loc], li[i]
return li
堆
def sift(li, low, high):
i = low
j = 2*i+1
tmp = li[i]
while j <= high:
if j < high and li[j] < li[j+1]:
j += 1
if li[j] > tmp:
li[i] = li[j]
i = j
j = 2*i+1
else:
break
li[i] = tmp
return li
def heap_sort(li):
n = len(li)
for i in range(n//2-1, -1, -1):
sift(li, i, n-1)
for j in range(n-1, -1, -1):
li[0], li[j] = li[j], li[0]
sift(li, 0, j-1)
return li
快排
def partition(li, left, right):
tmp = li[left]
while left < right:
while left < right and li[right] >= tmp:
right -= 1
li[left] = li[right]
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)
return li
def quick_sort(li):
_quick_sort(li, 0, len(li)-1)
return 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
return li
def _merge_sort(li, low, high):
if low < high:
mid = (low + high) // 2
_merge_sort(li, low, mid)
_merge_sort(li, mid+1, high)
merge(li, low, mid, high)
return li
def merge_sort(li):
_merge_sort(li, 0, len(li)-1)
return li
希尔
def shell_sort(li):
d = len(li) // 2
while d > 0:
for i in range(d, len(li)):
tmp = li[i]
j = i - d
while j >= 0 and li[j] > tmp:
li[j+d] = li[j]
j -= d
li[j+d] = tmp
d //= 2
计数
def count_sort(li, max_num):
count = [0 for _ in range(max_num)]
for num in li:
count[num] += 1
i = 0
for k, v in enumerate(count):
for j in range(v):
li[i] = k
i += 1
桶
def bucket_sort(li, n=100, max_num=1000):
buckets = [[] for _ in range(n)]
for num in li:
i = min(num//max_num//n, n-1)
buckets[i].append(num)
for j in range(len(buckets[i])-1, 0, -1):
if buckets[i][j] < buckets[i][j-1]:
buckets[i][j-1], buckets[i][j] = buckets[i][j], buckets[i][j-1]
else:
break
li.clear()
for buc in buckets:
li.extend(buc)
基数排序
def radix_sort(li):
max_num = max(li)
ini = 0
while 10 ** ini <= max_num:
buckets = [[] for _ in range(10)]
for num in li:
digit = (num // 10 ** ini) % 10
buckets[digit].append(num)
li.clear()
for buc in buckets:
li.extend(buc)
ini += 1