优化选择排序算法,大致思路是每次循环分别找到最大值和最小值,放到列表的头部和尾部
代码如下:
#! coding:utf8
import random
def select_sort(arr):
for i in range(len(arr) - 1):
min_position = i
max_position = i
for j in range(i + 1, len(arr) - i):
min_position = j if arr[min_position] > arr[j] else min_position
max_position = max_position if arr[max_position] > arr[j] else j
if arr[min_position] < arr[max_position]:
print(arr[min_position], arr[max_position])
start_pos = arr[i]
arr[i] = arr[min_position]
arr[min_position] = start_pos
for jj in range(i + 1, len(arr) - i):
max_position = max_position if arr[max_position] > arr[jj] else jj
end_pos = arr[-i - 1]
arr[-i - 1] = arr[max_position]
arr[max_position] = end_pos
print("循环结果:", arr)
if __name__ == "__main__":
arr_list = [each for each in range(20)]
random.shuffle(arr_list)
print("原始列表:", arr_list)
select_sort(arr_list)
随机产生一个长度为二十的乱序列表,进行排序,中间过程和结果如下:
原始列表: [9, 5, 1, 6, 2, 16, 15, 19, 7, 4, 10, 18, 17, 13, 0, 8, 11, 12, 14, 3]
0 19
循环结果: [0, 5, 1, 6, 2, 16, 15, 3, 7, 4, 10, 18, 17, 13, 9, 8, 11, 12, 14, 19]
1 18
循环结果: [0, 1, 5, 6, 2, 16, 15, 3, 7, 4, 10, 14, 17, 13, 9, 8, 11, 12, 18, 19]
2 17
循环结果: [0, 1, 2, 6, 5, 16, 15, 3, 7, 4, 10, 14, 12, 13, 9, 8, 11, 17, 18, 19]
3 16
循环结果: [0, 1, 2, 3, 5, 11, 15, 6, 7, 4, 10, 14, 12, 13, 9, 8, 16, 17, 18, 19]
4 15
循环结果: [0, 1, 2, 3, 4, 11, 8, 6, 7, 5, 10, 14, 12, 13, 9, 15, 16, 17, 18, 19]
5 14
循环结果: [0, 1, 2, 3, 4, 5, 8, 6, 7, 11, 10, 9, 12, 13, 14, 15, 16, 17, 18, 19]
6 13
循环结果: [0, 1, 2, 3, 4, 5, 6, 8, 7, 11, 10, 9, 12, 13, 14, 15, 16, 17, 18, 19]
7 12
循环结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 10, 9, 12, 13, 14, 15, 16, 17, 18, 19]
8 11
循环结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
9 10
循环结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]