Binary search algorithm (kotlin)

A sorted array, binary search for the target element:


fun main(args: Array<String>) {
    print(search(arrayOf(1, 3, 5, 6, 12, 54), 7))
}

fun search(nums: Array<Int>, target: Int): Int {
    var left = 0
    var right = nums.size
    var mid = (left + right).shr(1)

    while (left <= right) {
        if (target <= nums[mid]) {
            right = mid - 1
        } else {
            left = mid + 1
        }
        mid = (left + right).shr(1)
    }

    return left

}

Kotlin developer community

1233356-4cc10b922a41aa80

The public account of the first Kotlin developer community in China, which mainly shares and exchanges related topics such as Kotlin programming language, Spring Boot, Android, React.js / Node.js, functional programming, and programming ideas.

The more noisy the world, the more peaceful thinking is needed.

1665 original articles published · 1067 praised · 750,000 views

Guess you like

Origin blog.csdn.net/universsky2015/article/details/105265893