First strictly smaller element in a sorted array in Java | C ++ program to find first element that is strictly smaller than given target . ; Minimum size of the array should be 1 ; If target lies beyond the max element , than the index of strictly smaller value than target should be ( end - 1 ) ; Move to the left side if the target is smaller ; Move right side ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int next ( int arr [ ] , int target , int end ) { if ( end == 0 ) return -1 ; if ( target > arr [ end - 1 ] ) return end - 1 ; int start = 0 ; int ans = -1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( arr [ mid ] >= target ) { end = mid - 1 ; } else { ans = mid ; start = mid + 1 ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 5 , 8 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( next ( arr , 5 , n ) ) ; return 0 ; }