Nearest smaller character to a character K from a Sorted Array | C ++ Program to implement the above approach ; Function to return the nearest smaller character ; Stores the nearest smaller character ; Iterate till starts cross end ; Find the mid element ; Check if K is found ; Check if current character is less than K ; Increment the start ; Otherwise ; Increment end ; Return the character ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; char bs ( char ar [ ] , int n , int ele ) { int start = 0 ; int end = n - 1 ; char ch = ' @ ' ; while ( start <= end ) { int mid = start + ( end - start ) / 2 ; if ( ar [ mid ] == ele ) end = mid - 1 ; else if ( ar [ mid ] < ele ) { ch = ar [ mid ] ; start = mid + 1 ; } else end = mid - 1 ; } return ch ; } int main ( ) { char ar [ ] = { ' e ' , ' g ' , ' t ' , ' y ' } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; char K = ' u ' ; char ch = bs ( ar , n , K ) ; if ( ch == ' @ ' ) cout << " - 1" ; else cout << ch ; return 0 ; }