我之前看過一篇帖子,有人說解決方案是不要在內部 for 回圈之外進行交換。下面的演算法沒有,但仍然不適用于串列 A 僅 B
A = [4,2,7,-8,1,3,8,6,-1,-2]
B = [3,4,2,5,3,21,-7,3,26,-43,-12,22]
def selection_sort(list):
for i in range(len(list)-1):
smallest_index = i
#print('i: ', list[i])
for j in range(i 1,len(list)-1):
if list[j] < list[smallest_index]:
smallest_index = j
#print('j: ', list[j])
if smallest_index != i:
list[i], list[smallest_index] = list[smallest_index], list[i]
return list
selection_sort(B)
A的結果
[-43, -12, -7, 2, 3, 3, 3, 4, 5, 21, 22, 26, -2]
uj5u.com熱心網友回復:
for你的兩個回圈的界限都是錯誤的;兩個回圈的上限應該是len(list),而不是 len(list) - 1。(請記住,s 的上限range()是互斥的。)
這正確地對輸入進行排序:
B = [3,4,2,5,3,21,-7,3,26,-43,-12,22]
# Don't use list as a variable name; it shadows the list() builtin.
def selection_sort(input_list):
for i in range(len(input_list)):
smallest_index = i
for j in range(i 1, len(input_list)):
if input_list[j] < input_list[smallest_index]:
smallest_index = j
if smallest_index != i:
input_list[i], input_list[smallest_index] = \
input_list[smallest_index], input_list[i]
return input_list
print(selection_sort(B))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438324.html
標籤:Python python-3.x 算法 排序 选择排序
下一篇:骰子的獨特組合
