冒泡排序法请参考: https://blog.csdn.net/weixin_43801392/article/details/104809061
选择排序法请参考: https://blog.csdn.net/weixin_43801392/article/details/104858074
选择排序原理
选择排序是从数列中逐个取数, 每取一个数, 按照其数值大小, 依次插入到新数列中合适的位置.
例如对于如下数列
0
−
8
−
2
−
6
0-8-2-6
0−8−2−6
第一次取出第一个数, 放到第一位, 则存在两个数列, 分别是:
0
∣
8
−
2
−
6
0 | 8-2-6
0∣8−2−6
第二次取出第二个数, 在新数列中比较大小, 放到0的后面, 则新结果为:
0
−
8
∣
2
−
6
0-8|2-6
0−8∣2−6
同理, 第三轮:
0
−
2
−
8
∣
6
0-2-8|6
0−2−8∣6
第四轮:
0
−
2
−
6
−
8
0-2-6-8
0−2−6−8
对于长度为4的数列, 需要4轮排序才能完成.
python代码实现
首先, 还是建立一个生成随机数的程序: random_list.py
#-*- coding:utf-8 -*-
# Created Date: 2020/03/10
import random
def random_list(n):
"""返回一个长度为n的随机数列表,数值为[0,1000)"""
print("Input number is :{}\n".format(n))
iList = []
for num in range(n):
iList.append(random.randrange(1000))
return iList
if __name__ == "__main__":
iList = random_list(10)
print(iList)
然后, 建立插入排序算法的程序: insertSort.py
#-*- coding:utf-8 -*-
# Created Date: 2020/03/14
from random_list import random_list
import timeit
import sys
# 调用sys库argv函数从外部传入参数
num = sys.argv[1]
print("Number of list is: {}".format(num))
# 调用从random_list导入的ranmdon_list()函数生成随机数组
source_list = random_list(int(num))
def insertSort(source_list):
'''定义插入排序算法函数'''
if len(source_list) <= 1:
return source_list
for idx_a in range(1, len(source_list)):
# 取出当前数值
var = source_list[idx_a]
for idx_b in range(0, idx_a):
if var <= source_list[idx_b]:
# 在新数列中依次寻找≤var的数字,然后通过切片赋值移动大于var的数字,将var插入当前位置
source_list[idx_b+1:idx_a+1] = source_list[idx_b:idx_a]
source_list[idx_b] = var
break
return source_list
if __name__ == "__main__":
print("#"*20 + "\nSuccessful!\n" + "#"*20)
print("the original datas are: {}".format(source_list))
print("the sorted results are: {}".format(insertSort(source_list)))
print(timeit.timeit("insertSort(source_list)", "from __main__ import insertSort, source_list", number = 100))
程序编写完成后, 在命令行输入指令:
python insertSort.py 10
执行结果为:
Number of list is: 10
Input number is :10
####################
Successful!
####################
the original datas are: [413, 989, 807, 903, 701, 14, 501, 149, 787, 70]
the sorted results are: [14, 70, 149, 413, 501, 701, 787, 807, 903, 989]
0.0004693509999924572