排序算法-选择排序
- 选择排序
- 将序列中的最大值找出,然后跟最后一个元素交换位置
- 循环执行步骤1
- 优化函数并封装成函数
lst = [2, 5, 33, 6, 3, 8]
index = 0
for i in range(len(lst) - 1):
if lst[i + 1] > lst[index]:
index = i + 1
lst[index], lst[len(lst) - 1] = lst[len(lst) - 1], lst[index]
print(lst)
lst = [2, 5, 33, 6, 3, 8]
for i in range(len(lst) - 1):
index = 0
for j in range(len(lst) - 1 - i):
if lst[j + 1] > lst[index]:
index = j + 1
lst[index], lst[len(lst) - 1 - i] = lst[len(lst) - 1 - i], lst[index]
print(lst)
def sort(lst):
n = len(lst)
for i in range(n - 1):
index = 0
for j in range(n - 1 - i):
if lst[j + 1] > lst[index]:
index = j + 1
lst[index], lst[n - 1 - i] = lst[n - 1 - i], lst[index]
return lst
lst = [2, 5, 33, 6, 3, 8]
print(sort(lst))