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,913 questions

51,846 answers

573 users

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

1 Answer

0 votes
def ternary_search(l, r, key, lst):
    while l <= r:
        mid1 = l + (r - l) // 3
        mid2 = r - (r - l) // 3

        if lst[mid1] == key:
            return mid1
        if lst[mid2] == key:
            return mid2

        if key < lst[mid1]:
            r = mid1 - 1
        elif key > lst[mid2]:
            l = mid2 + 1
        else:
            l = mid1 + 1
            r = mid2 - 1

    return -1  # not found


def main():
    lst = [1, 2, 8, 14, 15, 64, 78, 89, 99, 100, 110, 123]
    to_search = 89

    index = ternary_search(0, len(lst) - 1, to_search, lst)

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


if __name__ == "__main__":
    main()



'''
run:

Element found at index: 7

'''

 



answered Jan 12 by avibootz
edited Jan 12 by avibootz

Related questions

...