python - 仅使用 For 循环在 Python 中实现插入排序

标签 python

我尝试仅使用 for 循环实现插入排序并编写了以下代码:

def isort(L):    #implementation with a for loop
    for i in range(1,len(L)):
        small = L[i]
        M = range(i)
        M.reverse()
        for j in M:
            if small<L[j]:
                L[j+1]=L[j]
            else:
                break
        L[j+1] = small
    return L

L = [5,4,3,2,1]
M = isort(L)
print M

这给出了输出 [5,1,2,3,4]。谁能指出我哪里出错了

最佳答案

更改(问题中显示的修复很简单,一次性错误是由一点点 +1 造成的:)):

L[j+1] = small

收件人:

L[j] = small

测试:

>>> isort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]

但是,如图所示,您的代码还有其他一些问题 - 它在很多时候都不起作用。通过一些调整,我们可以让它工作:

def isort(L):
    for i in range(1,len(L)):
        small = L[i]
        M = range(-1, i)
        M.reverse()
        for j in M:
            if j>=0 and small<L[j]:
                L[j+1]=L[j]
            else:
                break
        L[j+1] = small
    return L

测试:

>>> isort([4, 5, 3, 2, 1])
[1, 2, 3, 4, 5]

关于python - 仅使用 For 循环在 Python 中实现插入排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23028531/

相关文章:

python - 如何将python响应字符串转换为Json

python - 过滤 Pandas 数据框

python - 如何在python中为OneHotEncoded值和hashlib创建签名数字?

python - 如何在python中设置mfrow/mfcol

python - Dask dataframe - 根据分隔符将列拆分为多行

python - Nose 忽略使用自定义装饰器的测试

python - 如何检查一个数字是否是基数 b 的幂?

python - scipy hierarchy.linkage 和 Bray-Curtis 距离不一致

python - 为什么 Python 3 中的 `input` 抛出 NameError : name. .. 未定义

python - 拆分单元格中的文本并为标记创建额外的行