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
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.