Kotlin Program for Binary Search with Example
while loop to repeatedly divide the sorted array and compare the middle element with the target, like fun binarySearch(arr: IntArray, target: Int): Int which returns the index or -1 if not found.Examples
How to Think About It
Algorithm
Code
fun binarySearch(arr: IntArray, target: Int): Int {
var low = 0
var high = arr.size - 1
while (low <= high) {
val mid = (low + high) / 2
when {
arr[mid] == target -> return mid
arr[mid] < target -> low = mid + 1
else -> high = mid - 1
}
}
return -1
}
fun main() {
val arr = intArrayOf(1, 3, 5, 7, 9)
val target = 5
val result = binarySearch(arr, target)
println(result)
}Dry Run
Let's trace the search for target 5 in array [1, 3, 5, 7, 9].
Initialize pointers
low = 0, high = 4 (array indices)
Calculate mid
mid = (0 + 4) / 2 = 2
Compare mid element
arr[2] = 5 equals target 5, return 2
| low | high | mid | arr[mid] | comparison |
|---|---|---|---|---|
| 0 | 4 | 2 | 5 | 5 == 5, found target |
Why This Works
Step 1: Divide and conquer
The code splits the array into halves by calculating the middle index with mid = (low + high) / 2.
Step 2: Compare middle element
It compares the middle element with the target using arr[mid] == target to check if it found the target.
Step 3: Adjust search range
If the target is greater or smaller, it moves the low or high pointer to narrow the search to one half.
Step 4: Return result
If the target is found, it returns the index; otherwise, it returns -1 after the loop ends.
Alternative Approaches
fun binarySearchRecursive(arr: IntArray, target: Int, low: Int = 0, high: Int = arr.size - 1): Int { if (low > high) return -1 val mid = (low + high) / 2 return when { arr[mid] == target -> mid arr[mid] < target -> binarySearchRecursive(arr, target, mid + 1, high) else -> binarySearchRecursive(arr, target, low, mid - 1) } } fun main() { val arr = intArrayOf(1, 3, 5, 7, 9) println(binarySearchRecursive(arr, 5)) }
fun main() {
val arr = intArrayOf(1, 3, 5, 7, 9)
val index = arr.binarySearch(5)
println(index)
}Complexity: O(log n) time, O(1) space
Time Complexity
Binary search halves the search space each step, so it runs in logarithmic time relative to the array size.
Space Complexity
The iterative version uses constant extra space, only a few variables for pointers.
Which Approach is Fastest?
The built-in binarySearch is optimized and fastest for practical use; recursive is easier to understand but uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative binary search | O(log n) | O(1) | Memory efficient, fast |
| Recursive binary search | O(log n) | O(log n) | Clear logic, less memory efficient |
| Kotlin built-in binarySearch | O(log n) | O(1) | Quick and optimized for Kotlin |
low or high pointers correctly, causing infinite loops or wrong results.