gpt4 book ai didi

python - 在python中选择排序算法

转载 作者:行者123 更新时间:2023-12-04 08:42:26 25 4
gpt4 key购买 nike

我正在研究数据结构和算法,并定义了 [下面] 的函数来实现 选择排序算法 .... 但是,将最小值切换到数组开头的语句似乎不起作用。下面是函数定义:

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 {如果 i不是最小数目 min_number }
我已经尝试用这个数组(或 list,因为它在 python 中被调用)测试这个函数:
[5, 2, 3, 9, 8, 7]
结果失败,因为函数返回与输入的数组相同的数组。我这样做的原因是我想看看是否可以在不实现 2 for 的情况下实现 Select Sort 算法。循环。

最佳答案

线

array[_index], array[array.index(min_value)] = min_value, i
是相同的:
temp = (min_value, i)
array[_index] = temp[0]
array[array.index(min_value)] = temp[1]
一、 array[_index]设置为 min_value .这意味着(如果不是相同的最小值在数组中的先前索引中)接下来的 array.index(min_value)返回 _index .
简单的解决方案:交换表达式:
array[array.index(min_value)], array[_index] = i, min_value

关于python - 在python中选择排序算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64491276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com