【问题标题】:python swap sort not giving correct outputpython交换排序没有给出正确的输出
【发布时间】:2016-07-22 18:22:16
【问题描述】:

我正在尝试对从第二个数字开始的数组进行排序,并查看它之前的数字以查看前一个数字是否更大。如果是,我想交换数字,否则将数字保留在原处。目前我的代码没有这样做。当我在下面输入数组时,唯一改变的是 2 变成了 11,在中间给了我两个 11。出了什么问题?

#given an array of digits a of length N
a = [7, 3, 11, 2, 6, 16]
N = len(a)

# moving forward along a starting from the second position to the end

# define _sillysort(a, start_pos):
#     set position = start_pos
#     moving backwards along a from start_pos:
#         if the a[position-1] is greater than a[position]:
#             swap a[position-1] and a[position]
def sillysort(a, start_pos):
    a_sorted = []
    start_pos = a[1]
    for position in a:
        if a[start_pos-1] >= a[start_pos]:
            a[start_pos-1], a[start_pos] = a[start_pos], a[start_pos-1]
        else:
            a[start_pos-1] = a[start_pos]
        a_sorted.append(position)
        position += 1
    return a_sorted

当我运行这个 sillysort(a, N) 时,我得到这个输出 [7, 3, 11, 11, 6, 16]。

【问题讨论】:

    标签: python arrays sorting if-statement for-loop


    【解决方案1】:

    您的代码有几个问题

    start_pos = a[1]

    如果您已经提供 start_pos 作为函数的参数,为什么要在函数中重新初始化它。此外,如果a 是您要排序的数组,为什么您的算法的start_pos 是数组a 本身的第二个元素?

    for position in a:
            if a[start_pos-1] >= a[start_pos]:
                a[start_pos-1], a[start_pos] = a[start_pos], a[start_pos-1]
            else:
                a[start_pos-1] = a[start_pos]
            a_sorted.append(position)
            position += 1
    

    for in 循环将遍历数组aposition 将获取数组元素的值。在您的示例中,position 将按以下顺序获取值:

    7, 3, 11, 2, 6, 16

    我不明白你为什么在 for 循环结束时将位置增加 1。再一次,您使用数组中的值来索引数组而不是索引本身。

    由于在您的示例中,start_pos 将采用值 a[1] 即 3,您的代码比较 a[3] 和 a[2] 即 2 和 11 并进入 else 条件并使 a[3] = a[2] 因此你在 2 的位置得到 11

    您可能对变量名感到困惑。看看这对你有没有帮助。

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 2022-06-10
      • 2012-09-07
      • 2023-03-30
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多