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

1 Answer

0 votes
func ternarySearch(_ l: Int, _ r: Int, key: Int, in arr: [Int]) -> Int {
    var left = l
    var right = r

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

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

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

    return -1 // not found
}

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

    let index = ternarySearch(0, arr.count - 1, key: toSearch, in: arr)

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

main()


/*
run:

Element found at index: 7

*/

 



answered Jan 12 by avibootz

Related questions

...