python - 构造插入排序

标签 python sorting insertion-sort

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

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

这是我目前的代码

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/

相关文章:

c - 实现插入算法

python - 深度学习模型训练速度非常慢 Jetson Nano

python - 如何在这些数组中找到最大数量的可能正确匹配项?

java - 在 Java 中对自定义链表进行排序

arrays - 如何使用多个键 Swift 4 过滤两个字典?

c - c 插入排序错误

java - 这两种 Java 插入排序算法哪个更好?

python - OpenCV中的阈值未检测到我想要获取的完整对象。我怎样才能解决这个问题?

python httplib/urllib 获取文件名

c++ - 冒泡排序算法不起作用