Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

How to implement ternary search to find a value in a sorted list with Kotlin

1 Answer

0 votes
fun ternarySearch(l: Int, r: Int, key: Int, arr: List<Int>): Int {
    var left = l
    var right = r

    while (left <= right) {
        val mid1 = left + (right - left) / 3
        val mid2 = right - (right - left) / 3

        when {
            arr[mid1] == key -> return mid1
            arr[mid2] == key -> return mid2
            key < arr[mid1] -> right = mid1 - 1
            key > arr[mid2] -> left = mid2 + 1
            else -> {
                left = mid1 + 1
                right = mid2 - 1
            }
        }
    }

    return -1 // not found
}

fun main() {
    val arr = listOf(1, 2, 8, 14, 15, 64, 78, 89, 99, 100, 110, 123)
    val toSearch = 89

    val index = ternarySearch(0, arr.size - 1, toSearch, arr)

    if (index != -1) {
        println("Element found at index: $index")
    } else {
        println("Element not found.")
    }
}



/*
run:

Element found at index: 7

*/

 



answered Jan 12 by avibootz

Related questions

...