【问题标题】:How to do Python insertion sort on certain range of the list only?如何仅在列表的特定范围内进行 Python 插入排序?
【发布时间】:2021-03-30 02:51:30
【问题描述】:

所以,我尝试得到 [1, 2, 3, 5, -4] 但我想得到 [3, 1, 2, 5, -4] 作为结果;因为我只想从列表的索引 1 到索引 4 排序(包括开始,不包括结束;这意味着只从索引 1 到索引 3 排序,保持索引 0 和 4 不变)

def insertionSort(the_list, start, end):
    for mark in range(start, end):
        temp = the_list[mark]
        i = mark-1
        while i >= 0 and the_list[i] > temp:
            the_list[i+1] = the_list[i]
            i -= 1
        the_list[i+1] = temp

    return the_list

print(insertionSort([3, 2, 5, 1, -4], 1, 4))

有人可以帮我修复代码,以便我得到我想要的结果吗?谢谢。

【问题讨论】:

    标签: python insertion-sort


    【解决方案1】:

    您需要对要排序的部分进行切片。以下是我将如何实施。

    def insertionSort(alist,s, e):
    
        #check if s or e is greater than the length of the list
        if s >= len(alist) or e >= len(alist):
            #if True, then request is invalid
            return ('invalid request')
    
        #sort the list for the slice of data
        alist[s:e] = sorted(alist[s:e])
    
        # now return the full list 
        # The above code ensures you are not touching values before and after
        return alist
    
    print (insertionSort([3, 2, 5, 1, -4], 1, 4))
    

    这个输出将是:

    [3, 1, 2, 5, -4]
    

    对代码中问题的解释:

    您的 for 循环从头到尾开始。但是,您正在检查从 start - 1 开始的值(代码 i = mark - 1)。当标记为 1(开始)时,您将 i 设置为 0(标记 - 1 即 1 - 1 = 0)。这使您的代码考虑第 0 位。这就是为什么你得到1, 2, 3, 5, -4 作为输出。

    另外,如果您给出的值大于列表中元素的数量,您的代码将会崩溃。你也必须照顾这种情况。比如你给print (insertionSort([3, 2, 5, 1, -4], 1, 7)),代码就会崩溃。

    【讨论】:

      猜你喜欢
      • 2018-01-12
      • 2011-10-18
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 2015-04-06
      • 2014-11-06
      • 2021-05-21
      相关资源
      最近更新 更多