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

Python选择排序函数可排序数字无法排序单词问题求助

问题原因
  • 核心错误是交换操作的位置放置错误:选择排序的正确逻辑是先完整遍历未排序区间,找到最小值的索引后仅执行一次交换。你将交换逻辑放在了内层遍历循环内部,每找到一个更小的元素就立刻交换,会导致已锁定的i索引位置的元素被反复修改,后续比较的基准完全混乱。
  • 数字数组看似能正常排序只是巧合,该逻辑本身就是错误的,并非对字符串类型的数组无效。
修复方案

将交换逻辑移出内层for循环,等内层遍历完成、确定最终的最小值索引后再执行交换,修复后的代码如下:

nums = [10, 70, 30, 100, 40, 45, 90, 80, 85]
words = ["dog","at", "good", "eye", "cat", "ball", "fish"]

def selectionSort(anArray):
    length = range(0, len(anArray)-1)
    for i in length:
        minValue = i
        # 内层循环仅负责查找最小值索引,不执行交换
        for x in range(i+1, len(anArray)):
            if anArray[x] < anArray[minValue]:
                minValue = x
        # 找到最终最小值索引后再执行一次交换
        if minValue != i:
            anArray[minValue], anArray[i] = anArray[i], anArray[minValue]
    return anArray

selectionSort(nums)
selectionSort(words)
print(nums)
print(words)
运行结果

修复后代码输出如下,数字和字符串数组均可正常升序排序:

[10, 30, 40, 45, 70, 80, 85, 90, 100]
['at', 'ball', 'cat', 'dog', 'eye', 'fish', 'good']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:36:00