Search for an element in a Mountain Array | Function to find the index of the peak element in the array ; Stores left most index in which the peak element can be found ; Stores right most index in which the peak element can be found ; Stores mid of left and right ; If element at mid is less than element at ( mid + 1 ) ; Update left ; Update right ; Function to perform binary search in an a subarray if elements of the subarray are in an ascending order ; Stores mid of left and right ; If X found at mid ; If X is greater than mid ; Update left ; Update right ; Function to perform binary search in an a subarray if elements of the subarray are in an ascending order ; Stores mid of left and right ; If X found at mid ; Update right ; Update left ; Function to find the smallest index of X ; Stores index of peak element in array ; Stores index of X in the array ; If X greater than or equal to first element of array and less than the peak element ; Update res ; If element not found on left side of peak element ; Update res ; Print res ; Driver Code ; Given X ; Given array ; Function Call
function findPeak ( arr ) { var left = 0 ; var right = arr . length - 1 ; while ( left < right ) { var mid = left + parseInt ( ( right - left ) / 2 ) ; if ( arr [ mid ] < arr [ mid + 1 ] ) { left = mid + 1 ; } else { right = mid ; } } return left ; } function BS ( X , left , right , arr ) { while ( left <= right ) { var mid = left + parseInt ( ( right - left ) / 2 ) ; if ( arr [ mid ] == X ) { return mid ; } else if ( X > arr [ mid ] ) { left = mid + 1 ; } else { right = mid - 1 ; } } return - 1 ; } function reverseBS ( X , left , right , arr ) { while ( left <= right ) { var mid = left + parseInt ( ( right - left ) / 2 ) ; if ( arr [ mid ] == X ) { return mid ; } else if ( X > arr [ mid ] ) { right = mid - 1 ; } else { left = mid + 1 ; } } return - 1 ; } function findInMA ( X , mountainArr ) { var peakIndex = findPeak ( mountainArr ) ; var res = - 1 ; if ( X >= mountainArr [ 0 ] && X <= mountainArr [ peakIndex ] ) { res = BS ( X , 0 , peakIndex , mountainArr ) ; } if ( res == - 1 ) { res = reverseBS ( X , peakIndex + 1 , mountainArr . length - 1 , mountainArr ) ; } document . write ( res + " " ) ; } var X = 3 ; var X = 3 ; var list = [ 1 , 2 , 3 , 4 , 5 , 3 , 1 ] ; findInMA ( X , list ) ;