Ternary Search | Python3 program to illustrate recursive approach to ternary search ; Function to perform Ternary Search ; Find the mid1 and mid2 ; Check if key is present 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 ; The key lies in between l and mid1 ; The key lies in between mid2 and r ; The key lies in between mid1 and mid2 ; Key not found ; Driver code ; Get the array Sort the array if not sorted ; Starting index ; length of array ; Key to be searched in the array ; Search the key using ternarySearch ; Print the result ; Key to be searched in the array ; Search the key using ternarySearch ; Print the result
import math as mt NEW_LINE def ternarySearch ( l , r , key , ar ) : NEW_LINE INDENT if ( r >= l ) : NEW_LINE INDENT mid1 = l + ( r - l ) // 3 NEW_LINE mid2 = r - ( r - l ) // 3 NEW_LINE if ( ar [ mid1 ] == key ) : NEW_LINE INDENT return mid1 NEW_LINE DEDENT if ( ar [ mid2 ] == key ) : NEW_LINE INDENT return mid2 NEW_LINE DEDENT if ( key < ar [ mid1 ] ) : NEW_LINE INDENT return ternarySearch ( l , mid1 - 1 , key , ar ) NEW_LINE DEDENT elif ( key > ar [ mid2 ] ) : NEW_LINE INDENT return ternarySearch ( mid2 + 1 , r , key , ar ) NEW_LINE DEDENT else : NEW_LINE INDENT return ternarySearch ( mid1 + 1 , mid2 - 1 , key , ar ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT l , r , p = 0 , 9 , 5 NEW_LINE 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