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

为何结合选择排序与二分查找的Python代码查找目标值返回-1?

选择排序+二分查找返回-1的问题分析

输入列表[200, 12, 3, 100, 2],查找目标值100时输出索引-1,核心问题出在代码的逻辑顺序、排序实现、二分查找逻辑三个层面,具体错误点如下:

一、最直接的原因:函数提前返回

在selectionsort函数的外层for循环中,第一次迭代后直接执行了return -1,导致后续的二分查找代码完全没有机会运行,函数直接返回-1,这是输出-1的直接原因。

二、选择排序逻辑错误

选择排序的核心是找到当前未排序区间的最小值索引,再和当前起始位置交换,但你的代码实现完全错误:

  • 内层循环中每次都把min_idx = i,这会覆盖之前找到的最小值索引,正确逻辑应该是比较lst[i]和lst[min_idx],只有当lst[i]更小时才更新min_idx
  • 交换操作的时机错误,应该在找到整个未排序区间的最小值索引后,再和step位置交换,而不是每次内层循环都判断交换

三、二分查找逻辑错误

即使函数没有提前返回,二分查找的代码也无法正确工作:

  • 找到目标值lst[mid] == target时,没有return mid,只是写了mid,没有返回值
  • 边界调整逻辑完全搞反:
    • 当lst[mid] < target时,目标值应该在右半区间,需要把first = mid + 1,而不是mid - 1
    • 当lst[mid] > target时,目标值应该在左半区间,需要把last = mid - 1,而不是mid + 1
  • 循环结束后返回None,但你的verify函数对None的处理是输出“Target not found”,不符合常规的索引返回逻辑(未找到返回-1)

四、代码结构不合理

将选择排序和二分查找耦合在一个函数里,不仅逻辑混乱,也不利于调试和复用,建议拆分为两个独立函数:一个负责排序,一个负责查找。


修正后的代码示例

def selection_sort(lst):
    # 正确的选择排序实现
    for step in range(len(lst)):
        min_idx = step
        # 找到未排序区间的最小值索引
        for i in range(step + 1, len(lst)):
            if lst[i] < lst[min_idx]:
                min_idx = i
        # 交换当前起始位置和最小值位置
        lst[step], lst[min_idx] = lst[min_idx], lst[step]

def binary_search(lst, target):
    first = 0
    last = len(lst) - 1
    while first <= last:
        mid = (first + last) // 2
        if lst[mid] == target:
            return mid
        elif lst[mid] < target:
            first = mid + 1
        else:
            last = mid - 1
    # 未找到返回-1
    return -1

def verify(index):
    if index != -1:
        print("Target found at index", index)
    else:
        print("Target not found")

data = [200, 12, 3, 100, 2]
selection_sort(data)
result = binary_search(data, 100)
verify(result)
print("The sorted list is", data)

运行这段代码后,会输出:

Target found at index 3
The sorted list is [2, 3, 12, 100, 200]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:21:06