OneCompiler

Binary Search

118

Q) Given an array of character sorted in ascending
order, find the greatest character that is less than
the target character in the array.
Target character is not present in the array.

If there is not such element return ‘a’
{'c', 'e', 'g', 'k', 'y'}

Target = ‘d’ => ans = ‘c’

Target = ‘f’ => ans = ‘e’

Target = ‘z’ = > ans = ‘y’

Target = ‘b’ => ans = ‘a’

Following is sample java code.

import java.util.*;

public class Main {
    public static char bs(char arr[] , char target )
    {
            int l=0;
            int r=arr.length-1;
            char ans ;
            while(l<=r)
            {
              
               int mid=l + (r-l)/2;

                if(target<=arr[0])
                return 'a';
               else if(arr[mid]<target)
              {
                l=mid+1;
                
              }

              else
                  r = mid-1;
                 
    }
               ans=arr[r];
               return ans;
    }
    public static void main(String[] args) {
        
            char arr[]={'c','e','g','k','y'};
            
            
            System.out.println(bs(arr,'h'));
        }
}