可能最简单的排序策略就是:
1.搜索整个列表,找到最小项的位置
2.如果该位置不是列表的第一项,则将两项交换位置
3.然后算法回到第二个位置并重复上述操作
4.当算法到达列表最后一个位置的时候,排序就完成了
首先我们需要定义一个用于交换位置的函数
def swap(lyst, i, j):
"""Exchanges the elements at positions i and j."""
temp = lyst[i]
lyst[i] = lyst[j]
lyst[j] = temp
下面是排序函数
def selectionSort(lyst):
i = 0
while i < len(lyst) - 1:
minIndex = i #首先设置第一项为最小项
j = i + 1
while j < len(lyst): # Start a search
if lyst[j] < lyst[minIndex]:
minIndex = j
j += 1
if minIndex != i: # Exchange if needed
swap(lyst, minIndex, i)
i += 1