【发布时间】:2021-02-06 00:05:15
【问题描述】:
我正在研究数据结构和算法,我定义了函数 [below] 来实现 选择排序算法....但是,将最小值切换到数组开头的语句并没有'似乎没有工作。这是函数定义:
def selectionSort(array: list):
array_length = len(array) # this just stores the length of the given list
_index = 0 # this takes care of dynamically changing the index in which a minimum value is to be found
for i in array:
min_value = min(array[_index:array_length])
if i == min_value: # if i is the minimum value then do nothing, however update _index
_index += 1
continue
else: # if i is not the minimum value....
array[_index], array[array.index(min_value)] = min_value, i # replace i with the minimum number, and move i to the [now previous] position of the minimum number,
_index += 1 # don'f forget to update _index
return array
特定命令array[_index], array[array.index(min_value)] = min_value, i 似乎不起作用,它实际上负责将数组min_value 中最小值的位置与数组i 中的当前评估值切换{如果@987654325 @不是最小数字min_number}
我已尝试使用此数组(或在 python 中调用的list)测试此函数:
[5, 2, 3, 9, 8, 7]
当函数返回失败的结果时,返回与输入的相同的数组。我这样做的原因是我想看看是否可以在不实现 2 个for 循环的情况下实现选择排序算法。
【问题讨论】:
标签: python arrays list algorithm sorting