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 ; 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
< ? php function ternarySearch ( $ l , $ r , $ key , $ ar ) { if ( $ r >= $ l ) { $ mid1 = ( int ) ( $ l + ( $ r - $ l ) / 3 ) ; $ mid2 = ( int ) ( $ r - ( $ r - $ l ) / 3 ) ; if ( $ ar [ $ mid1 ] == $ key ) { return $ mid1 ; } if ( $ ar [ $ mid2 ] == $ key ) { return $ mid2 ; } if ( $ key < $ ar [ $ mid1 ] ) { return ternarySearch ( $ l , $ mid1 - 1 , $ key , $ ar ) ; } else if ( $ key > $ ar [ $ mid2 ] ) { return ternarySearch ( $ mid2 + 1 , $ r , $ key , $ ar ) ; } else { return ternarySearch ( $ mid1 + 1 , $ mid2 - 1 , $ key , $ ar ) ; } } return -1 ; } $ ar = array ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ) ; $ l = 0 ; $ r = 9 ; $ key = 5 ; $ p = ternarySearch ( $ l , $ r , $ key , $ ar ) ; echo " Index ▁ of ▁ " , $ key , " ▁ is ▁ " , ( int ) $ p , " STRNEWLINE " ; $ key = 50 ; $ p = ternarySearch ( $ l , $ r , $ key , $ ar ) ; echo " Index ▁ of ▁ " , $ key , " ▁ is ▁ " , ( int ) $ p , " STRNEWLINE " ; ? >