【问题标题】:Insertion sort using python (what is the issue here, i`m not getting any error but this program won`t run)使用 python 进行插入排序(这里有什么问题,我没有收到任何错误,但这个程序不会运行)
【发布时间】:2017-02-06 18:45:54
【问题描述】:
def insertion_sort(list):
    for index in range(1,len(list)):
        value=list[index]
        i=index-1
        while i>=0:
            if value<list[1]:
                list[i+1]=list[i]  # shift no in slot i to i+1
                list[i]=value   # shift value left into slot i
                i=i-1
            else:
                break
k =input("enter no of elements")
print(insertion_sort(k))

【问题讨论】:

  • 你的函数没有返回任何东西,所以我不确定你期望打印什么。
  • 非常感谢朋友!

标签: python loops insertion-sort


【解决方案1】:

您忘记了 return 语句,您在 if 语句中控制了错误的索引。

def insertion_sort(list):
    for index in range(1,len(list)):
        value=list[index]
        i=index-1
        while i>=0:
            if value<list[i]: # careful on here
                list[i+1]=list[i]  # shift no in slot i to i+1
                list[i]=value   # shift value left into slot i
                i=i-1
            else:
                break
    return list

values = raw_input("enter values:") # 6 2 4 7 2 1 8
values = [ int(x) for x in values.split(' ') ] # then use this values array in insertion_sort function
print(insertion_sort(values))

这将打印 1,2,2,4,6,7,8

【讨论】:

  • 非常感谢您的帮助。我可以这样跑。但我想输入数组作为输入,而不是硬编码。我该怎么做?
  • def insert_sort(list): for index in range(1,len(list)): value=list[index] i=index-1 while i>=0: if value
  • 您可以使用 raw_input 作为字符串来获取值,用一个空白字符分隔每个数字,并使用列表推导将它们转换为 int 数组。
  • values = raw_input("enter values:") # 6 2 4 7 2 1 8 values = [ int(x) for x in values.split(' ') ] # 然后使用这个值数组在 insert_sort 函数中。我已经更新了我的代码。
  • 如果我参考互联网找到我需要输入数组的部分是否可以。我应该有罪吗? :D :(
猜你喜欢
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 2021-09-02
  • 2019-04-16
  • 2011-12-12
  • 2016-06-24
  • 1970-01-01
相关资源
最近更新 更多