1.插入排序:
def nsert_sort(list):
for i in range(len(list)):
for j in range(i):
if list[i] < list[j]:
list.insert(j, list.pop(i))
break
return list
list = nsert_sort([4, 5, 6, 7, 3, 2, 6, 9, 8])
print(list)
2.冒泡排序
def bubble_sort(list):
count = len(list)
for i in range(0, count):
for j in range(i + 1, count):
if list[i] > list[j]:
list[i], list[j] = list[j], list[i]
return list
list = bubble_sort([4, 5, 6, 7, 3, 2, 6, 9, 8])
print(list)
3.快速排序
def quick_sort(list):
count = len(list)
if count <= 1:
return list
pivot = list[count // 2]
left = [x for x in list if x < pivot]
middle = [x for x in list if x == pivot]
right = [x for x in list if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
if __name__ == '__main__':
list = [4, 5, 6, 7, 3, 2, 6, 9, 8]
print(quick_sort(list))
4.基数排序
def radix_sort(array):
bucket, digit = [[]], 0
while len(bucket[0]) != len(array):
bucket = [[], [], [], [], [], [], [], [], [], []]
for i in range(len(array)):
num = (array[i] // 10 ** digit) % 10
bucket[num].append(array[i])
array.clear()
for i in range(len(bucket)):
array += bucket[i]
digit += 1
return array
5.归并排序
def merge_sort(array):
def merge_arr(arr_l, arr_r):
array = []
while len(arr_l) and len(arr_r):
if arr_l[0] <= arr_r[0]:
array.append(arr_l.pop(0))
elif arr_l[0] > arr_r[0]:
array.append(arr_r.pop(0))
if len(arr_l) != 0:
array += arr_l
elif len(arr_r) != 0:
array += arr_r
return array
def recursive(array):
if len(array) == 1:
return array
mid = len(array) // 2
arr_l = recursive(array[:mid])
arr_r = recursive(array[mid:])
return merge_arr(arr_l, arr_r)
return recursive(array)
文章转载:https://www.cnblogs.com/xingxingnbsp/p/10635573.html