text: Search an element in a reverse sorted array | C program for the above approach ; 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
code: #include <stdio.h> NEW_LINE int binarySearch ( int arr [ ] , int N , int X ) { int start = 0 ; int end = N ; while ( start <= end ) { int mid = start + ( end - start ) / 2 ; if ( X == arr [ mid ] ) { return mid ; } else if ( X < arr [ mid ] ) { start = mid + 1 ; } else { end = mid - 1 ; } } return -1 ; } int main ( ) { int arr [ ] = { 5 , 4 , 3 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 4 ; int res = binarySearch ( arr , N , X ) ; printf ( " ▁ % d ▁ " , res ) ; return 0 ; }