Find the number of elements greater than k in a sorted array | Function to return the count of elements from the array which are greater than k ; Stores the index of the left most element from the array which is greater than k ; Finds number of elements greater than k ; If mid element is greater than k update leftGreater and r ; If mid element is less than or equal to k update l ; Return the count of elements greater than k ; Driver code
< ? php function countGreater ( $ arr , $ n , $ k ) { $ l = 0 ; $ r = $ n - 1 ; $ leftGreater = $ n ; while ( $ l <= $ r ) { $ m = $ l + ( int ) ( ( $ r - $ l ) / 2 ) ; if ( $ arr [ $ m ] > $ k ) { $ leftGreater = $ m ; $ r = $ m - 1 ; } else $ l = $ m + 1 ; } return ( $ n - $ leftGreater ) ; } $ arr = array ( 3 , 3 , 4 , 7 , 7 , 7 , 11 , 13 , 13 ) ; $ n = sizeof ( $ arr ) ; $ k = 7 ; echo countGreater ( $ arr , $ n , $ k ) ;