2 回答

TA贡献1744条经验 获得超4个赞
这应该有效。它还使用 range() 来避免使用 while 循环。
def selSort(l):
'''Sorts the list in descending order using a selection sort algorithm.
Params: l (list): unsorted list
Sorts: unsorted list in descending order
'''
for i in range(len(l)):
# Find the largest element in list
max_index = i
for j in range(i + 1, len(l)):
if l[max_index] < l[j]:
max_index = j
# Swap the first and max item
l[i], l[max_index] = l[max_index], l[i]

TA贡献1946条经验 获得超4个赞
选择排序算法的逻辑(降序):是对表进行 n-1 次迭代(n 是列表中的元素数)。在第 i 次迭代中,我们选择索引 i+1 和 n 之间的最高元素,并将该元素与列表中位置 i 的元素交换。这导致以下代码:
def selSort(l):
'''Sorts the list in descending order using a selection sort algorithm.
Params: l (list): unsorted list
Sorts: unsorted list in descending order
'''
for i in range(len(l)-1) :
posMax = i
for j in range(i+1,len(l)):
if l[j] > l[posMax]:
posMax = j
l[posMax], l[i] = l[i], l[posMax]
return l
l = selSort([242, 18, 44, 201, 1111])
print(l) #prints [1111, 242, 201, 44, 18]
添加回答
举报