Ternary Search | Function to perform Ternary Search ; Find mid1 and mid2 ; Check if key is at any mid ; Since key is not present at mid , Check in which region it is present Then repeat the search operation in that region ; key lies between l and mid1 ; key lies between mid2 and r ; key lies between mid1 and mid2 ; key not found ; Get the list Sort the list if not sorted ; Starting index ; Length of list ; Key to be searched in the list ; Search the key using ternary search ; Print the result ; Key to be searched in the list ; Search the key using ternary search ; Print the result
def ternarySearch ( l , r , key , ar ) : NEW_LINE INDENT while r >= l : NEW_LINE INDENT mid1 = l + ( r - l ) // 3 NEW_LINE mid2 = r - ( r - l ) // 3 NEW_LINE if key == ar [ mid1 ] : NEW_LINE INDENT return mid1 NEW_LINE DEDENT if key == mid2 : NEW_LINE INDENT return mid2 NEW_LINE DEDENT if key < ar [ mid1 ] : NEW_LINE INDENT r = mid1 - 1 NEW_LINE DEDENT elif key > ar [ mid2 ] : NEW_LINE INDENT l = mid2 + 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = mid1 + 1 NEW_LINE r = mid2 - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT ar = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] NEW_LINE l = 0 NEW_LINE r = 9 NEW_LINE key = 5 NEW_LINE p = ternarySearch ( l , r , key , ar ) NEW_LINE print ( " Index ▁ of " , key , " is " , p ) NEW_LINE key = 50 NEW_LINE p = ternarySearch ( l , r , key , ar ) NEW_LINE print ( " Index ▁ of " , key , " is " , p ) NEW_LINE