算法思路:
每次选出最小的,放入第一个位置,
再一趟排序记录列表无序区最小的数,放第二个位置
算法关键点:有序区和无序区,无序区最小的数
时间复杂度:O(n^2)
1.简单版-代码:
import
def select_sort_simple(lst):
"""create new list, callback min & remove"""
lst_new = []
for i in range(len(lst)):
min_loc = min(lst)
lst_new.append(min_loc)
lst.remove(min_loc)
print(lst_new)
return lst_new
lst = [random.randint(0, 100) for x in range(10)]
print(lst)
print(select_sort_simple(lst))
结果:
[33, 67, 92, 15, 39, 23, 10, 53, 95, 25]
[10]
[10, 15]
[10, 15, 23]
[10, 15, 23, 25]
[10, 15, 23, 25, 33]
[10, 15, 23, 25, 33, 39]
[10, 15, 23, 25, 33, 39, 53]
[10, 15, 23, 25, 33, 39, 53, 67]
[10, 15, 23, 25, 33, 39, 53, 67, 92]
[10, 15, 23, 25, 33, 39, 53, 67, 92, 95]
[10, 15, 23, 25, 33, 39, 53, 67, 92, 95]
上面方法可以说是选择排序的简单实现,但存在几个问题,min(),remove()其实也是O(n)级别,而且开辟新的列表,消耗内存,如果序列很大,内存资源消耗大,不建议用。
下面的相当于升级版,改善之处在于,不用开辟新的序列,另外做到能抠则抠,尽量减少不必要的循环,选择排序推荐使用。
2.升级版-代码:
import random
def select_srot(lst):
for i in range(len(lst)-1): # i是第几趟
min_loc = i
for j in range(i+1, len(lst)): # j是无序区, 从i+1开始
if lst[min_loc] > lst[j]:
min_loc = j
lst[i], lst[min_loc] = lst[min_loc], lst[i]
print(lst)
lst = [random.randint(0, 100) for x in range(10)]
print(lst)
print(select_srot(lst))
结果:
[3, 22, 92, 84, 97, 52, 27, 39, 1, 63]
[1, 22, 92, 84, 97, 52, 27, 39, 3, 63]
[1, 3, 92, 84, 97, 52, 27, 39, 22, 63]
[1, 3, 22, 84, 97, 52, 27, 39, 92, 63]
[1, 3, 22, 27, 97, 52, 84, 39, 92, 63]
[1, 3, 22, 27, 39, 52, 84, 97, 92, 63]
[1, 3, 22, 27, 39, 52, 84, 97, 92, 63]
[1, 3, 22, 27, 39, 52, 63, 97, 92, 84]
[1, 3, 22, 27, 39, 52, 63, 84, 92, 97]
[1, 3, 22, 27, 39, 52, 63, 84, 92, 97]