本文实例讲述了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
|
#!/usr/bin/python
# coding:utf-8
#直接插入排序
def insert_sort( list ):
for i in range ( len ( list )):
key = list [i] #待插入元素
j = i - 1
while (key < list [j] and j > = 0 ):
list [j + 1 ] = list [j] #后移元素
list [j] = key
j = j - 1
return list
#冒泡排序
def bubble_sort( list ):
for i in range ( 1 , len ( list )):
for j in range ( len ( list ) - i):
if list [j] > list [j + 1 ]:
list [j + 1 ], list [j] = list [j], list [j + 1 ]
return list
#快速排序
def position_key( list , low, high):
i = low
j = high
key = list [low]
while (i < j):
while (i < j and list [j] > = key): #从右向左,寻找第一个小于基准元素的数据索引。 注意:i<y 的判断,内循环更新j
j - = 1
if i < j :
list [i] = list [j]
while (i<j and list [i] < = key): #从左向右,寻找地一个大于基准元素的数据索引。i<y同上
i + = 1
if i < j:
list [j] = list [i]
list [j] = key # 基准元素位置
return j
def quick_sort( list , low, high):
if low < high:
position = position_key( list , low, high) #将数据分成前后两个子序列(前边序列值均小于后边序列)
quick_sort( list , low, position - 1 ) #将前面的序列快速排序
quick_sort( list , position + 1 , high) #将后面的序列快速排序
return list
#选择排序
def select_sort( list ):
for i in range ( len ( list )):
for j in range (i, len ( list )):
if list [i] > list [j]:
list [i], list [j] = list [j], list [i]
return list
list = [ 23 , 232 , 11 , 89 , 121 , 64 , 34 , 12 , 23423 , 2312 , 167 , 768 , 932 , 346 , 32789 , 335 , 2 , 1145 , 34 , 56 , 99 , 111 ]
print '原始序列 :' , list
print '直接插入排序:' , insert_sort( list )
print '冒泡排序 :' , bubble_sort( list )
print '快速排序 :' , quick_sort( list , 0 , len ( list ) - 1 )
print '选择排序 :' , select_sort( list )
|
结果如下:
原始序列 : [23, 232, 11, 89, 121, 64, 34, 12, 23423, 2312, 167, 768, 932, 346, 32789, 335, 2, 1145, 34, 56, 99, 111]
直接插入排序: [2, 11, 12, 23, 34, 34, 56, 64, 89, 99, 111, 121, 167, 232, 335, 346, 768, 932, 1145, 2312, 23423, 32789]
冒泡排序 : [2, 11, 12, 23, 34, 34, 56, 64, 89, 99, 111, 121, 167, 232, 335, 346, 768, 932, 1145, 2312, 23423, 32789]
快速排序 : [2, 11, 12, 23, 34, 34, 56, 64, 89, 99, 111, 121, 167, 232, 335, 346, 768, 932, 1145, 2312, 23423, 32789]
选择排序 : [2, 11, 12, 23, 34, 34, 56, 64, 89, 99, 111, 121, 167, 232, 335, 346, 768, 932, 1145, 2312, 23423, 32789]
希望本文所述对大家python程序设计有所帮助。
原文链接:https://blog.csdn.net/King0217/article/details/78785293