You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

插入排序(Insertion Sort)第4次迭代j值为3的运行逻辑咨询

插入排序第4次迭代j值为3的逻辑解释

你提供的插入排序代码如下:

def insertionSort(array):
    for i in range(1, len(array)):
        j = i
        while j > 0 and array[j - 1] > array[j]:
            print('array[j-1]', array[j - 1], 'array[j]', array[j])
            swap(j, j - 1, array)
            j -= 1
            print('j', j)
    return array

def swap(i, j, array):
    array[i], array[j] = array[j], array[i]

前置说明

迭代计数规则:代码中for i in range(1, len(array))从i=1开始遍历,第1次迭代对应i=1,第4次迭代对应i=4。
测试用例初始数组:[8, 5, 2, 9, 5, 6, 3]
前3次迭代(i=1、i=2、i=3)处理完成后,数组状态为[2, 5, 8, 9, 5, 6, 3]。

第4次迭代执行步骤

  1. 进入i=4的迭代逻辑,首先执行j = i赋值,此时j的初始值为4
  2. 校验while循环条件:j>0成立,且array[j-1] = array[3] = 9,array[j] = array[4] =5,满足9>5,进入循环体
  3. 调用swap函数交换索引3和4的元素,数组变为[2, 5, 8, 5, 9, 6, 3]
  4. 执行j -= 1语句,j从4减少为3,后续打印j 3,就是你观测到j变为3的原因

后续逻辑会继续校验while循环条件,此时j=3>0,且array[2] = 8 > array[3] =5,会继续交换元素,j继续递减,直到不满足循环条件为止。

内容的提问来源于stack exchange,提问作者dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 09:45:03