【问题标题】:Select Sort Algorithm in python在python中选择排序算法
【发布时间】: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


    【解决方案1】:

    线

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-06
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 2019-04-24
      • 2019-03-31
      • 1970-01-01
      相关资源
      最近更新 更多