ternary search is a divide and conquer algorithm that can be used to find an element in an array it is similar to binary search where we divide the array into two parts but in this algorithm we divide the given array into three parts and determine which has the key searched element we can divide the array into three parts by taking mid1 and mid2 initially l and r will be equal to 0 and n1 respectively where n is the length of the array mid1 l rl3 mid2 r rl3 note array needs to be sorted to perform ternary search on it tn olog3n log3 log base 3 find the given value key in an array sorted in ascending order returns the index of the value if found and 1 otherwise if the index is not in the range left right ie left index right returns 1 key lies between l and mid1 key lies between mid2 and r key lies between mid1 and mid2 key not found find the given value key in an array sorted in ascending order returns the index of the value if found and 1 otherwise if the index is not in the range left right ie left index right returns 1 key lies between l and mid1 key lies between mid2 and r key lies between mid1 and mid2 key not found
def ternary_search(left, right, key, arr):
    

    while right >= left:
        mid1 = left + (right-left) // 3
        mid2 = right - (right-left) // 3

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

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

    
    return -1