gpt4 book ai didi

python - 构造插入排序

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:00 25 4
gpt4 key购买 nike

我在插入排序方面遇到了麻烦,我觉得我可能错过了排序的要点并且误解了基本原理。

我们得到了一个插入排序,它编辑了输入其中的数组。我们的任务是修改给定的代码,然后创建一个不会编辑原始数组的建设性插入排序

这是我目前的代码

def append(A, x):
return A + [x]

def insertionSort(A):
B = []
B = append(B, A[0])
for i in range(1, len(A)):
B = insert(B, A[i], i, A)
return str(B)

def insert(B, k, hi, A):
print(B, k, hi)
for x in range(hi-1, -1, -1):
if B[x] <= k:
B = append(B, k)
return B
B = append(B, A[x])
B[0] = k
return B

print(insertionSort([2,4,6,8,10,1,3,5,7,9]))

然而,在列表中的第三个或第四个元素之后,它开始以相反的顺序将所有项目添加到列表的末尾


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

我无法理解为什么这是错误的。

非常感谢任何可以提供帮助的人。

最佳答案

逆向问题是在insert函数中的foor循环当您的循环达到这些值时,它会启动反向模式

def insert(B, k, hi, A):
# when hi=5
for x in range(hi-1, -1, -1):
# x = 4
# here B[4] is 10 and k=1 so B[4] <= 1 is False
# you program does not execute the inside of if
# instead it jumps to B = append(B, A[x]) where A[4] == 10
# and the this loop goes in reverse mode from 4 to 0
# when x = 3
# B[x] = 8 so 8 is not less or equal of k where k = 1
# so it jumps again to B = append(B, A[x]) where A[x] = A[3] = 8
# so it append 8
# and so on
# when this loop is finished your list will look like [1,4,6,8,10,10,8,6,4,2]
# the 1 gets added when the loop is finished at B[0] = k
# and then rest of the outputs are result of the loop inside the insertionSort func
if B[x] <= k:
B = append(B, k)
return B
B = append(B, A[x])
B[0] = k
return B

解决方法:

def insertionSort(A):
copy_sort = A.copy()

for i in range(1, len(copy_sort)):
item = copy_sort[i]

j = i - 1
while j >= 0 and copy_sort[j] > item:
copy_sort[j + 1] = copy_sort[j]
j -= 1
copy_sort[j + 1] = item

return copy_sort


your_array = [2,4,6,8,10,1,3,5,7,9]
sorted = insertionSort(your_array)
print(your_array)
print(sorted)

关于python - 构造插入排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58438827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com