Search in an array of strings where non | Java program to find location of a str in an array of strings which is sorted and has empty strings between strings . ; Compare two string equals are not ; Main function to find string location ; Move mid to the middle ; If mid is empty , find closest non - empty string ; If mid is empty , search in both sides of mid and find the closest non - empty string , and set mid accordingly . ; If str is found at mid ; If str is greater than mid ; If str is smaller than mid ; Driver Code ; Input arr of Strings . ; input Search String
import java . util . * ; class GFG { static int compareStrings ( String str1 , String str2 ) { int i = 0 ; while ( i < str1 . length ( ) - 1 && str1 . charAt ( i ) == str2 . charAt ( i ) ) i ++ ; if ( str1 . charAt ( i ) > str2 . charAt ( i ) ) return - 1 ; if ( str1 . charAt ( i ) < str2 . charAt ( i ) ) return 1 ; else return 0 ; } static int searchStr ( String [ ] arr , String str , int first , int last ) { if ( first > last ) return - 1 ; int mid = ( last + first ) / 2 ; if ( arr [ mid ] . isEmpty ( ) ) { int left = mid - 1 ; int right = mid + 1 ; while ( true ) { if ( left < right && right > last ) return - 1 ; if ( right <= last && ! arr [ right ] . isEmpty ( ) ) { mid = right ; break ; } if ( left >= right && ! arr [ left ] . isEmpty ( ) ) { mid = left ; break ; } right ++ ; left -- ; } } if ( compareStrings ( str , arr [ mid ] ) == 0 ) return mid ; if ( compareStrings ( str , arr [ mid ] ) < 0 ) return searchStr ( arr , str , mid + 1 , last ) ; return searchStr ( arr , str , first , mid - 1 ) ; } public static void main ( String [ ] args ) { String [ ] arr = { " for " , " " , " " , " " , " geeks " , " ide " , " " , " practice " , " " , " " , " quiz " , " " , " " } ; String str = " quiz " ; int n = arr . length ; System . out . println ( searchStr ( arr , str , 0 , n - 1 ) ) ; } }