为什么我不能运行我的代码?(插入排序算法)?

2024-09-29 22:17:06 发布

您现在位置:Python中文网/ 问答频道 /正文

def insertionSort(lst):
    k = 1
    while k < len(lst):
        x = lst.pop(k)
        insertInOrder(lst, k, x)
        k += 1

def insertInOrder(lst, k, x):
    while k >= 1 and lst[k-1] > x:
        k -= 1
        lst.insert(k, x)

这是我到目前为止所做的代码,但我对python还不熟悉,无法让它运行。我是否缺少print语句或集合?你知道吗


Tags: and代码lendef语句popinsertprint
1条回答
网友
1楼 · 发布于 2024-09-29 22:17:06

insertInOrder中的第一个while测试中有一个小错误。这是修复过的版本。我添加了一个print调用,这样您就可以看到排序过程。你知道吗

def insertionSort(lst):
    k = 1
    while k < len(lst):
        x = lst.pop(k)
        insertInOrder(lst, k, x)
        k += 1

def insertInOrder(lst, k, x):
    print(k, x, lst)
    while k > 0 and lst[k-1] > x:
        k -= 1
    lst.insert(k, x)

a = [4, 5, 7, 2, 9]
print(a)
insertionSort(a)
print(a)

输出

[4, 5, 7, 2, 9]
1 5 [4, 7, 2, 9]
2 7 [4, 5, 2, 9]
3 2 [4, 5, 7, 9]
4 9 [2, 4, 5, 7]
[2, 4, 5, 7, 9]

相关问题 更多 >

    热门问题