- 选择排序/核心算法
- 每一趟两两比较大小,找出极值(极大值或极小值)并放置到有序区的位置(index交换)
simple_list = [[2, 9, 4, 10, 6, 8, 7], [7, 8, 5, 9, 3], [7, 8, 5, 9, 3, 4, 10, 6, 8, 7]]
choices = simple_list[0]
len_choices = len(choices)
for i in range(len_choices - 1):
maxindex = i
for j in range(i + 1, len_choices):
if choices[maxindex] < choices[j]:
maxindex = j
if maxindex != i:
choices[i], choices[maxindex] = choices[maxindex], choices[i]
print(choices)
[10, 9, 8, 7, 6, 4, 2]
simple_list = [[2, 9, 4, 10, 6, 8, 7], [7, 8, 5, 9, 3], [7, 8, 5, 9, 3, 4, 10, 6, 8, 7]]
choices = simple_list[0]
len_choices = len(choices)
for i in range(len_choices//2):
maxindex = i
minindex = -i-1
minorigin = minindex
for j in range(i + 1, len_choices-i):
if choices[maxindex] < choices[j]:
maxindex = j
if choices[minindex] > choices[-j-1]:
minindex = -j-1
if maxindex != i:
choices[i], choices[maxindex] = choices[maxindex], choices[i]
if minindex != minorigin:
choices[minorigin], choices[minindex] = choices[minindex], choices[minorigin]
print(choices)
- 注:
两次交换最大值交换后最小值索引没有跟着数字一起变换,逻辑错误出现BUG
simple_list = [[2, 9, 4, 10, 6, 8, 7], [7, 8, 5, 9, 3], [7, 8, 5, 9, 3, 4, 10, 6, 8, 7]]
choices = simple_list[2]
len_choices = len(choices)
for i in range(len_choices//2):
maxindex = i
minindex = -i-1
minorigin = minindex
for j in range(i + 1, len_choices-i):
if choices[maxindex] < choices[j]:
maxindex = j
if choices[minindex] > choices[-j-1]:
minindex = -j-1
if choices[minindex] == choices[maxindex]:
break
if maxindex != i:
choices[i], choices[maxindex] = choices[maxindex], choices[i]
if i == minindex or i == len_choices + minindex:
minindex = maxindex - len_choices
if minindex != minorigin:
choices[minorigin], choices[minindex] = choices[minindex], choices[minorigin]
print(choices)
[10, 9, 8, 8, 7, 7, 6, 5, 4, 3]