"""
选择排序:
思路:
遍历整个列表,找到最小项的位置。
如果该位置不是列表的第一个位置,算法就会交换这两个位置的项;
然后算法回到第二个位置并重复这个过程
"""
import random
#定义一个交换函数
def swap(lyst,i,j):
temp = lyst[i]
lyst[i] = lyst[j]
lyst[j] = temp
#定义选择排序
def selection_sort(lyst):
i = 0
while i < len(lyst) - 1:
min_index = i
j = i + 1
while j < len(lyst): #遍历当前子列表寻找最小项index
if lyst[j] < lyst[min_index]:
min_index = j
j += 1
if min_index != i:
swap(lyst,min_index,i)
i += 1
return lyst
def test_sort():
lyst = list(range(10))
lyst = random.shuffle(lyst)
assert selection_sort(lyst) == lyst
if __name__ == "__main__":
test_sort()
09_数据结构与算法_选择排序_Python实现
猜你喜欢
转载自blog.csdn.net/PyDarren/article/details/83449142
今日推荐
周排行