【问题标题】:I am trying to sort this array in python using selection sort algorithm but it doesn't give the desired output. What am I doing wrong?我正在尝试使用选择排序算法在 python 中对这个数组进行排序,但它没有给出所需的输出。我究竟做错了什么?
【发布时间】:2021-08-21 17:01:23
【问题描述】:

这是我的代码:

a = [3,7,10,1,9,6,8,5,4]
for i in a:
    if i < len(a) - 1:
        min = i
        for j in a:
            if j < len(a):
                if a[j] < a[min]:
                    min = j
        if min != i:
            temp = a[min]
            a[min] = a[i]
            a[i] = temp
        j += 1
    i += 1

print(a)

这是我得到的输出:

[3, 8, 10, 5, 1, 7, 9, 6, 4]

我在这方面做错了什么?对于我的问题的详细回答,我将不胜感激。

【问题讨论】:

  • 首先,您认为 i 和 j 是索引 (0, 1, ...),但它们是元素值 (3, 7, ...)。将一个值与数组的长度进行比较或使用该值作为索引取另一个值是没有意义的。
  • @SergioTulentsev 但是,我将如何给出条件: 1. 检查 i 的值是否小于等于元素数 - 1 2. 同样检查 j 的值是否为等于元素个数
  • 和你现在的完全一样。只是i 和j 应该是索引,而不是值。

标签: arrays python-3.x sorting for-loop selection-sort


【解决方案1】:

我相信您可能在代码中混淆了该特定索引的索引和数组的值。我已尝试使代码尽可能与您的代码相似,但我已将 i 重命名为 indexI 并将 j 重命名为 indexJ,以便更清楚地表明它们是索引而不是值。我也把min改成了indexMinimum:

a = [3,7,10,1,9,6,8,5,4]

for indexI in range(len(a)):
    
    indexMinimum = indexI
    
    for indexJ in range(indexI+1, len(a)):
        if a[indexJ] < a[indexMinimum] :
            indexMinimum = indexJ
            
    if a[indexMinimum] != a[indexI]:
        a[indexI], a[indexMinimum] = a[indexMinimum], a[indexI]

print ("The arranged array is: ", str(a))

希望你觉得它有用:)

【讨论】:

    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    相关资源
    最近更新 更多