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

不使用sort()重排数组:while循环提前终止问题求助

问题分析与解决方案

核心问题

你的代码提前终止的原因是while循环条件错误:
(count < len(arr)-1) and (arr[count] < arr[count+1])这个条件意味着,只要count到达数组倒数第二位,或者遇到第一个逆序对(arr[count] > arr[count+1]),循环就会立即终止,完全无法执行后续的交换和检查逻辑。此外,原代码中count +=1后直接访问arr[count+1],当count增长到len(arr)-1时还会触发索引越界错误。

修正后的实现(符合你的思路)

以下代码实现了你想要的逻辑:遇到逆序元素就交换,回退计数器重新检查前面的元素,直到整个数组有序:

arr = [7, 14, 21, 32, 17, 48, 69, 78, 72]
count = 0
n = len(arr)

# 持续循环直到数组完全有序
while True:
    swapped = False
    while count < n - 1:
        if arr[count] > arr[count + 1]:
            # 交换逆序元素
            arr[count], arr[count + 1] = arr[count + 1], arr[count]
            swapped = True
            # 回退计数器,检查前面的元素是否需要调整
            count = count - 1 if count > 0 else count + 1
        else:
            # 当前元素有序,前进到下一个
            count += 1
    # 一轮遍历无交换,说明数组已完全有序
    if not swapped:
        break
    # 重置计数器,准备下一轮检查
    count = 0

print(count)
print(arr)

逻辑说明

  1. 外层while True循环:作为总循环,直到某一轮遍历中没有发生任何交换(swapped为False)时终止,此时数组完全有序。
  2. 内层循环:逐个检查相邻元素,遇到逆序就交换,并回退计数器(如果不是第一个元素),确保前面的元素也能被正确验证;元素有序时则递增计数器继续检查。
  3. 每轮遍历结束后重置计数器,从头开始新一轮检查,避免遗漏未排序的元素。

简化替代方案(冒泡排序)

如果只是需要实现不调用sort()的数组排序,标准冒泡排序的实现更简洁高效:

arr = [7, 14, 21, 32, 17, 48, 69, 78, 72]
n = len(arr)

for i in range(n):
    swapped = False
    # 每轮遍历到未排序的最后一个元素
    for j in range(0, n - i - 1):
        if arr[j] > arr[j + 1]:
            arr[j], arr[j + 1] = arr[j + 1], arr[j]
            swapped = True
    # 无交换则提前终止,无需继续遍历
    if not swapped:
        break

print(arr)

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

相关产品推荐
方舟 Agent Plan

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

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