Kotlin Array - binarySearch() Function



The Kotlin array binarySearch() function is used to search a provided element from an array using the binary search algorithm.

The array should be sorted in order based on the Comparable natural ordering of its elements (comparator); otherwise, the result is undefined.

following are the exceptions of this function −

  • IndexOutOfBoundsException: If the fromIndex is less than zero or toIndex is greater than the size of this array.
  • IllegalArgumentException: If the fromIndex is greater than toIndex.
This function has no guarantee which will be found if the array contains multiple elements equal to the specified element.

Syntax

Following is the syntax of Kotlin array binarySearch() function −

fun <T> Array<out T>.binarySearch(
   element: T,
   comparator: Comparator<in T>,
   fromIndex: Int = 0,
   toIndex: Int = size
): Int

Parameters

This function accepts following parameters −

  • element: It is an element to be searched.

  • comparator: It is a comparator according to which this array is sorted.

  • fromIndex: It represents start of the range (inclusive) to search in, 0 by default.

  • toIndex: It represents end of the range (exclusive) to search in, size of this array by default.

Return value

This function returns index of the element, if it is contained in the array within the specified range; otherwise, the inverted insertion point (-insertion point - 1).

The insertion point is the index at which the element should be inserted.

Example 1

Following is the basic example to demonstrate the use of binarySearch() function −

fun main(args: Array<String>) {
   val numbers: Array<Int> = arrayOf(1, 2, 3, 4, 5)
   val index = numbers.binarySearch(2)
   println("Element fount at index: $index")
}

Output

Following is the output −

Element fount at index: 1

Example 2

Now, let's see another example. We create an array of size eight that is sorted in ascending order. We then use the binarySearch() function to find the index of particular element −

fun main(args: Array<String>) {
   // Create a sorted array
   val numbers = arrayOf(1, 3, 5, 7, 9, 11, 13, 15)

   val searchElement = 7

   // use the binarySearch()
   val index = numbers.binarySearch(searchElement)

   if (index >= 0) {
      println("Element $searchElement found at index $index")
   } else {
      println("Element $searchElement not found. Insertion point: ${-index - 1}")
   }
}

Output

Following is the output −

Element 7 found at index 3

Example 3

The example below creates an array of 5 integer that is not in sorted order. We then use binarySearch() to see whether we are getting the index of element −

fun main() {
   // create an unsorted array
   val numbers = arrayOf(3, 1, 7, 5, 9)
   val searchElement = 7
   
   // Check if the array is sorted
   if (isSorted(numbers)) {
      //use the binarySearch()
      val index = numbers.binarySearch(searchElement)
      if (index >= 0) {
         println("Element $searchElement found at index $index")
      } else {
         println("Element $searchElement not found. Insertion point: ${-index - 1}")
      }
   } else {
       println("Undefined: The array is not sorted.")
   }
}
fun isSorted(array: Array<Int>): Boolean {
   for (i in 0 until array.size - 1) {
      if (array[i] > array[i + 1]) {
         return false
      }
   }
   return true
}

Output

Following is the output −

Undefined: The array is not sorted.

Example 4

The example below shows the "IndexOutOfBoundsException" if the element is not available in the array −

fun main() {
   val numbers = arrayOf(1, 3, 5, 7, 9, 11, 13, 15)

   try { 
      // Perform a binary search for an element not in the array
      val invalidIndex = numbers.binarySearch(20)
      
      // This will throw IndexOutOfBoundsException because the index is negative
      println("Element at invalid index $invalidIndex: ${numbers[invalidIndex]}")
   } catch (e: IndexOutOfBoundsException) {
      println("IndexOutOfBoundsException caught: ${e.message}")
   }
}

Output

Following is the output −

IndexOutOfBoundsException caught: Index -9 out of bounds for length 8
kotlin_arrays.htm
Advertisements