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

自制升序排序算法异常排查及空初始列表实现求助

问题:实现逐个移入的升序排序算法(修复索引错误与排序逻辑)

需要实现将list1元素逐个移入list2的升序排序算法,已知有更优算法但希望自行实现。当前代码以list2=[-1]初始化,处理到元素6712时排序逻辑出错,最终触发IndexError: list index out of range。需求如下:

  • 将list2初始化为空列表
  • 排查修复排序异常及索引错误
  • 考虑用函数实现但不知如何入手

原代码

list1 = [3,1,2,8,4,73,6,9,14,12,6712,23,76,111,312,42]
list2 = [-1]
w = 0

for i in range(len(list1)):
    while w != len(list1):
        
        if list1[w] > list2[w]:
            list2.append(list1[w])
            print(list2)
            w+=1
        elif list1[w] < list2[w]:
            if list1[w] < list2[w-1]:
                list2.insert(w-1,list1[w])
                print(list2)
                w+=1 
            list2.insert(w,list1[w])
            print(list2)          
            w+=1
    break
print(list2)

原输出

[-1, 3]
[-1, 1, 3]
[-1, 1, 2, 3]
[-1, 1, 2, 3, 8]
[-1, 1, 2, 3, 4, 8]
[-1, 1, 2, 3, 4, 8, 73]
[-1, 1, 2, 3, 4, 6, 8, 73]
[-1, 1, 2, 3, 4, 6, 8, 9, 73]
[-1, 1, 2, 3, 4, 6, 8, 9, 14, 73]
[-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 73]
[-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 6712, 73]
[-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 73]
[-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73]
[-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73, 111]
[-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73, 111, 312]
[-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73, 42, 111, 312]
Traceback (most recent call last):
  File "C:/Users/alexi/Downloads/test.py", line 17, in <module>
    list2.insert(w,list1[w])
IndexError: list index out of range

问题分析

  1. 索引越界原因:用变量w同时作为list1的遍历索引和list2的比较索引,当list2长度随插入操作变化后,w会超过list2的有效索引范围,触发IndexError。
  2. 排序逻辑错误:仅和list2[w]、list2[w-1]比较,未遍历list2找到正确的插入位置,导致大元素(如6712)插错位置,后续小元素(如23、42)无法插入到正确的升序位置。
  3. 冗余逻辑:外层for循环加break完全多余,实际只执行了一次循环,逻辑混乱。

修复后的代码(函数实现)

def insert_sort_move(source_list):
    target_list = []
    for num in source_list:
        # 遍历目标列表,找到当前元素应插入的位置
        inserted = False
        for idx in range(len(target_list)):
            if num < target_list[idx]:
                target_list.insert(idx, num)
                inserted = True
                break
        # 若当前元素比目标列表所有元素都大,直接追加到末尾
        if not inserted:
            target_list.append(num)
        print(target_list)
    return target_list

# 测试执行
list1 = [3,1,2,8,4,73,6,9,14,12,6712,23,76,111,312,42]
sorted_list = insert_sort_move(list1)
print("最终排序结果:", sorted_list)

修复说明

  • 空列表初始化:target_list初始化为空,符合需求。
  • 独立索引处理:遍历source_list的每个元素,对每个元素单独遍历target_list找插入位置,避免共享索引导致的越界问题。
  • 完整排序逻辑:找到第一个比当前元素大的位置插入,确保target_list始终保持升序;若元素是最大的则追加到末尾。
  • 函数封装:将排序逻辑封装为函数,结构清晰,复用性强,便于维护和测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:03:02