简单选择排序
算法说明简单选择排序是一种选择排序。选择排序:每趟从待排序的记录中选出关键字最小的记录,顺序放在已排序的记录序列末尾,直到全部排序结束为止。python示例代码#!/usr/bin/env pythonimport randomarray = []# generat random listfor n in range(10):array.append(random.randint(1
·
算法说明
简单选择排序是一种选择排序。
选择排序:每趟从待排序的记录中选出关键字最小的记录,顺序放在已排序的记录序列末尾,直到全部排序结束为止。
python示例代码
#!/usr/bin/env python
import random
array = []
# generat random list
for n in range(10):
array.append(random.randint(1, 20))
print('before sort:', array)
for x in range(0, len(array)-1):
minIndex = x
# found minIndex
for y in range(x+1, len(array)):
if array[y] < array[minIndex]:
minIndex = y
# sway x and minIndex
if x != minIndex:
tmp = array[x]
array[x] = array[minIndex]
array[minIndex] = tmp
print('sorting...round', x+1, ':', array)
print('after sort:', array)
运行结果示例
before sort: [19, 17, 18, 5, 12, 7, 11, 18, 13, 18]
sorting...round 1 : [5, 17, 18, 19, 12, 7, 11, 18, 13, 18]
sorting...round 2 : [5, 7, 18, 19, 12, 17, 11, 18, 13, 18]
sorting...round 3 : [5, 7, 11, 19, 12, 17, 18, 18, 13, 18]
sorting...round 4 : [5, 7, 11, 12, 19, 17, 18, 18, 13, 18]
sorting...round 5 : [5, 7, 11, 12, 13, 17, 18, 18, 19, 18]
sorting...round 6 : [5, 7, 11, 12, 13, 17, 18, 18, 19, 18]
sorting...round 7 : [5, 7, 11, 12, 13, 17, 18, 18, 19, 18]
sorting...round 8 : [5, 7, 11, 12, 13, 17, 18, 18, 19, 18]
sorting...round 9 : [5, 7, 11, 12, 13, 17, 18, 18, 18, 19]
after sort: [5, 7, 11, 12, 13, 17, 18, 18, 18, 19]
算法时间复杂度
简单排序的时间复杂度为O(N2) (N平方,这个markdown编辑器打不出来)
更多推荐
已为社区贡献1条内容
所有评论(0)