气泡排序python中的外循环

发布于 2025-02-13 01:32:32 字数 327 浏览 0 评论 0原文

气泡排序的规范Python实现看起来像这样:

array = [5,2,7,8,1,6,3]
n = len(array)

for i in range(n):
    for j in range(n-i-1): 
        if array[j] > array[j+1]:
            array[j],array[j+1] = array[j+1], array[j]

现在,我的理解是外圈的总数应为n-1,其中n是数组大小。但是,在上面的Python代码中,范围会产生序列0,1,2,3,4,5,6并通过循环进行7次迭代?我在这里想念什么?

The canonical python implementation of bubble sort looks like this:

array = [5,2,7,8,1,6,3]
n = len(array)

for i in range(n):
    for j in range(n-i-1): 
        if array[j] > array[j+1]:
            array[j],array[j+1] = array[j+1], array[j]

Now, my understanding is the total number of passes of the outer loop should be n-1 where n is the array size. However, in the python code above, range produces the sequence 0,1,2,3,4,5,6 and iterates through the loop 7 times? What am I missing here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文