Sling Academy
Home/Kotlin/Using `binarySearch` with Sorted Arrays in Kotlin

Using `binarySearch` with Sorted Arrays in Kotlin

Last updated: December 04, 2024

Kotlin's binarySearch function is a powerful tool that allows developers to search for a specific value in a sorted array or list in logarithmic time. This means that the time it takes to find an element is proportional to the logarithm of the number of elements, making it an efficient choice for large collections.

Binary search works by repeatedly dividing the sorted list into halves until it finds the target value, if present. This method requires the list or array to be sorted beforehand. Consequently, you achieve better performance compared to linear search, especially with larger datasets.

Using `binarySearch` in Kotlin

Kotlin standard library provides a convenient binarySearch function for arrays and lists. Here, we will delve into how to use this function effectively.

Example of `binarySearch` with Arrays

Let’s say we have a sorted array of integers. We can quickly find the index of a specified element using the binarySearch function.

fun main() {
    val sortedArray = arrayOf(1, 3, 5, 7, 9, 11)
    val targetValue = 5
    val resultIndex = sortedArray.binarySearch(targetValue)

    if (resultIndex >= 0) {
        println("Element found at index: $resultIndex")
    } else {
        println("Element not found in the array.")
    }
}

In this example, binarySearch will return the index 2 since the target element 5 is located at that position in the array.

Dealing with Element Not Found

If the element is not found, binarySearch returns a negative insertion point flag, which is -(insertion point) - 1. This result can provide insights into where the target could be inserted, maintaining the order of the array.

fun main() {
    val sortedArray = arrayOf(2, 4, 6, 8, 10)
    val targetValue = 5
    val resultIndex = sortedArray.binarySearch(targetValue)

    if (resultIndex >= 0) {
        println("Element found at index: $resultIndex")
    } else {
        println("Element not found. Can be inserted at index: ${-resultIndex - 1}")
    }
}

Here, the program indicates that 5 is not present and suggests it could be inserted at index 2.

Working with Lists

The binarySearch function isn’t limited to arrays; it can also be used with lists in Kotlin. The usage is similar, as shown below:

fun main() {
    val sortedList = listOf(1.0, 2.5, 3.8, 4.4, 5.9)
    val targetValue = 3.8
    val resultIndex = sortedList.binarySearch(targetValue)

    if (resultIndex >= 0) {
        println("Element found at index: $resultIndex")
    } else {
        println("Element not found in the list.")
    }
}

Here, you effectively use binarySearch on a List of Double values, and it works in precisely the same way.

Conclusion

In Kotlin, the binarySearch function offers a straightforward API for conducting efficient searches within sorted arrays and lists. It's a fundamental technique that every Kotlin developer should be familiar with, especially when dealing with large datasets where performance can be an issue.

Remember to ensure your data structure is sorted before applying binarySearch to guarantee accurate results. This function is a staple in utilizing Kotlin’s rich libraries effectively, simplifying tasks and enhancing code execution.

Next Article: Reversing an Array in Kotlin

Previous Article: Converting Arrays to Lists, Sets, or Maps in Kotlin

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin