Search an element in a reverse sorted array | Function to search if element X is present in reverse sorted array ; Store the first index of the subarray in which X lies ; Store the last index of the subarray in which X lies ; Store the middle index of the subarray ; Check if value at middle index of the subarray equal to X ; Element is found ; If X is smaller than the value at middle index of the subarray ; Search in right half of subarray ; Search in left half of subarray ; If X not found ; Driver Code
function binarySearch ( arr , N , X ) { let start = 0 ; let end = N ; while ( start <= end ) { let mid = Math . floor ( start + ( end - start ) / 2 ) ; if ( X == arr [ mid ] ) { return mid ; } else if ( X < arr [ mid ] ) { start = mid + 1 ; } else { end = mid - 1 ; } } return - 1 ; } let arr = [ 5 , 4 , 3 , 2 , 1 ] ; let N = arr . length ; let X = 5 ; document . write ( binarySearch ( arr , N , X ) ) ;