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

1 Answer

0 votes
package main

import (
    "fmt"
)

func ternarySearch(l, r, key int, arr []int) int {
    for l <= r {
        mid1 := l + (r-l)/3
        mid2 := r - (r-l)/3

        if arr[mid1] == key {
            return mid1
        }
        if arr[mid2] == key {
            return mid2
        }

        if key < arr[mid1] {
            r = mid1 - 1
        } else if key > arr[mid2] {
            l = mid2 + 1
        } else {
            l = mid1 + 1
            r = mid2 - 1
        }
    }

    return -1 // not found
}

func main() {
    arr := []int{1, 2, 8, 14, 15, 64, 78, 89, 99, 100, 110, 123}
    toSearch := 89

    index := ternarySearch(0, len(arr)-1, toSearch, arr)

    if index != -1 {
        fmt.Println("Element found at index:", index)
    } else {
        fmt.Println("Element not found.")
    }
}


/*
run:

Element found at index: 7

*/

 



answered Jan 12 by avibootz

Related questions

...