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

Kotlin中基于抽象类实现二分搜索运行报错求助

Kotlin二分搜索代码报错排查及修复

核心错误点

  • 二分搜索逻辑错误:

    1. 边界判断错误:原代码if(r >= 1)应为if(r >= l),否则当左边界l大于1时会直接返回-1,无法完成有效搜索。
    2. 中间索引计算错误:var mid:Int=1+(r-1)/2会导致索引偏移,正确写法是l + (r - l) / 2,既避免整数溢出,又保证索引指向数组有效位置。
  • 抽象类使用不符合要求:
    任务要求使用抽象类,但当前print抽象类既未定义抽象方法,也未利用继承特性——Function方法里直接实例化BinarySearch对象,完全浪费了继承关系,未体现抽象类的设计意义。

  • 命名与拼写问题:
    Kotlin遵循小驼峰命名方法、大驼峰命名类的规则,原代码中BinarySearchFunction、displayMassage、Function、print、display均不符合规范;同时displayMassage存在拼写错误(应为displayMessage)。

修复后的代码

open class BinarySearch() {
    fun binarySearchFunction(arr: Array<Int>, l: Int, r: Int, x: Int): Int {
        if (r >= l) {
            val mid = l + (r - l) / 2
            if (arr[mid] == x) {
                return mid
            }
            return if (arr[mid] > x) {
                binarySearchFunction(arr, l, mid - 1, x)
            } else {
                binarySearchFunction(arr, mid + 1, r, x)
            }
        }
        return -1
    }

    open fun displayMessage(message: String) {}
}

abstract class Print : BinarySearch() {
    abstract fun performSearch() // 定义抽象方法,符合抽象类使用要求
}

class Display : Print() {
    override fun displayMessage(message: String) {
        println(message)
    }

    override fun performSearch() {
        val a = arrayOf(2, 3, 4, 10, 40)
        val n = a.size
        val x = 10
        val result = binarySearchFunction(a, 0, n - 1, x)
        if (result == -1) {
            println("Element not present")
        } else {
            println("Element found at index $result")
        }
    }
}

fun main() {
    val dis = Display()
    dis.displayMessage("The Binary Search : ")
    dis.performSearch()
}

修复说明

  1. 修正二分搜索的边界判断和中间索引计算逻辑,确保搜索逻辑正确。
  2. 调整抽象类Print,新增抽象方法performSearch,子类Display实现该方法并直接调用父类的binarySearchFunction,真正发挥继承与抽象类的设计作用。
  3. 统一修正所有命名,符合Kotlin编码规范,同时修复拼写错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 07:55:18