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
function ternarySearch ( l , r , key , ar ) { while ( r >= l ) { let mid1 = l + parseInt ( ( r - l ) / 3 , 10 ) ; let mid2 = r - parseInt ( ( r - l ) / 3 , 10 ) ; if ( ar [ mid1 ] == key ) { return mid1 ; } if ( ar [ mid2 ] == key ) { return mid2 ; } if ( key < ar [ mid1 ] ) { r = mid1 - 1 ; } else if ( key > ar [ mid2 ] ) { l = mid2 + 1 ; } else { l = mid1 + 1 ; r = mid2 - 1 ; } } return - 1 ; } let l , r , p , key ; let ar = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] ; l = 0 ; r = 9 ; key = 5 ; p = ternarySearch ( l , r , key , ar ) ; document . write ( " " + key + " " + p + " " ) ; key = 50 ; p = ternarySearch ( l , r , key , ar ) ; document . write ( " " + key + " " + p ) ;