[英]How to do Python insertion sort on certain range of the list only?
所以,我尝试得到 [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))
有人可以帮我修复代码,以便我可以得到我想要的结果吗? 谢谢你。
您需要对要排序的部分进行切片。 以下是我将如何实施。
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))
output 将是:
[3, 1, 2, 5, -4]
代码中问题的解释:
您的 for 循环从头到尾开始。 但是,您正在检查从 start - 1 开始的值(代码 i = mark - 1)。 当标记为 1(开始)时,您将 i 设置为 0(标记 - 1 即 1 - 1 = 0)。 这使您的代码考虑第 0 个 position。 这就是为什么你得到 1、2、3、5 1, 2, 3, 5, -4
作为 output。
此外,如果您给出的值大于列表中元素的数量,您的代码将崩溃。 你也必须照顾这种情况。 比如你给print (insertionSort([3, 2, 5, 1, -4], 1, 7))
,代码就会崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.