package com.secspace.sms.util

import android.util.Log

object Binary {

    fun binarySearch(array: List<String>, target: String): Boolean {
        var left = 0
        var right = array.size-1

        while (left <= right) {
            val mid = left + (right - left) / 2
            Log.e("shuju", "----MainActivity----查找结果 array[mid]:${array[mid]}  target:$target  mid:$mid")
            if (array[mid] == target) {
                return true // 目标值在数组中的索引
            } else if (array[mid] < target) {
                left = mid + 1
            } else {
                right = mid - 1
            }
        }

        return false // 未找到目标值
    }


    fun binarySearch0(
        a: List<String>, fromIndex: Int, toIndex: Int,
        key: String
    ): Int {
        var low = fromIndex
        var high = toIndex - 1

        while (low <= high) {
            val mid = (low + high) ushr 1
            val midVal = a[mid]

            if (midVal < key) low = mid + 1
            else if (midVal > key) high = mid - 1
            else return mid // key found
        }
        return -(low + 1) // key not found.
    }
}
