Kotlin实现二分查找

版本一

找到目标元素时返回其下标,未找到时返回-1

fun binarySearch(list: ArrayList<Int>, target: Int): Int {
    return binarySearch(list, target, 0, list.size - 1)
}

fun binarySearch(list: ArrayList<Int>, target: Int, minIndex: Int, maxIndex: Int): Int {
    if (minIndex > maxIndex) return -1
    val mid = (minIndex + maxIndex) / 2
    return when {
        target == list[mid] -> mid
        target > list[mid] -> binarySearch(list, target, mid + 1, maxIndex)
        target < list[mid] -> binarySearch(list, target, minIndex, mid - 1)
        else -> -1
    }
}

版本二

找到目标元素时返回其下标,未找到时 返回其应该插入的位置(在该位置插入后,数组仍保持有序)

fun binarySearch(list: ArrayList<Int>, target: Int): Int {
    return search(list, target, 0, list.size - 1)
}

fun binarySearch(list: ArrayList<Int>, target: Int, minIndex: Int, maxIndex: Int): Int {
    if (minIndex > maxIndex) return -1
    if (target < list[minIndex]) return minIndex
    if (target > list[maxIndex]) return maxIndex + 1
    val mid = (minIndex + maxIndex) / 2
    return when {
        target == list[mid] -> mid
        target > list[mid] -> search(list, target, mid + 1, maxIndex)
        target < list[mid] -> search(list, target, minIndex, mid - 1)
        else -> -1
    }
}

猜你喜欢

转载自blog.csdn.net/mrokayan/article/details/79750600