常见排序算法的python实现
以下代码实现的排序算法有:选择排序,冒泡排序,插入排序,希尔排序,归并排序,快速排序1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100# -*- coding:utf-8 -*-
li = [23, 12, 43, 45, 54, 514, 412, 543, 123, 534, 675, 1232]
def select_sort(li):
# 选择排序
for i in range(len(li)):
for j in range(i, len(li)):
if li[i] > li[j]:
li[i], li[j] = li[j], li[i]
return li
print(select_sort(li))
def bubble_sort(li):
# 冒泡排序
for i in range(len(li)):
for j in range(1, len(li) - i):
if li[j] < li[j - 1]:
li[j], li[j - 1] = li[j - 1], li[j]
return li
print(bubble_sort(li))
def insert_sort(li):
# 插入排序
for i in range(1, len(li)):
key = li[i]
j = i - 1
while j >= 0:
if key < li[j]:
li[j + 1] = li[j]
li[j] = key
j -= 1
return li
print(insert_sort(li))
def shell_sort(li):
# 希尔排序
gap = len(li) % 2
while gap > 0:
for i in range(gap, len(li)):
if li[i] < li[i - gap]:
li[i - gap], li[i] = li[i], li[i - gap]
return li
print(shell_sort(li))
def merge_sort(l1, l2):
# 归并排序
l3 = []
j = 0
for i in range(len(l1)):
while j < len(l2) and l1[i] > l2[j]:
l3.append(l2[j])
j += 1
l3.append(l1[i])
if j < len(l2) - 1:
while j < len(l2):
l3.append(l2[j])
j += 1
return l3
list1 = [1, 3, 5, 7, 9]
list2 = [2, 4, 6, 8, 10, 11, 12, 13, 14]
print(merge_sort(list1, list2))
def quick_sort(li, start, end):
# 快速排序
if start < end:
index = kp(li, start, end)
quick_sort(li, index +1, end)
quick_sort(li, start, index)
return li
def kp(li, start, end):
# 快速排序用来排序的函数
base = li[start]
while start < end:
while base <= li[end] and start < end:
end -= 1
while start < end and base > li[end]:
li[start], li[end] = li[end], li[start]
start += 1
return start
print(quick_sort(li, 0, len(li) - 1))