Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 14, 2015 09:59
Show Gist options
  • Save charlespunk/5068606 to your computer and use it in GitHub Desktop.
Save charlespunk/5068606 to your computer and use it in GitHub Desktop.
Given a sorted array of strings which is interepersed with empty strings, write a method to find the location of a given string.
public static int findLocation(int begin, int end, String input, String[] array){
if(begin > end) return -1;
int mid = (begin + end) / 2;
int leftEnd = mid - 1;
int rightBegin = mid + 1;
if(array[mid] == ""){
while(true){
if(leftEnd < 0 && rightBegin >= array.length) return -1;
else if(leftEnd >= 0 && array[leftEnd] != ""){
mid = leftEnd;
leftEnd--;
break;
}
else if(rightBegin < array.length && array[rightBegin] != ""){
mid = rightBegin;
rightBegin++;
break;
}
leftEnd--;
rightBegin++;
}
}
if(array[mid].equals(input)) return mid;
int num = findLocation(begin, leftEnd, input, array);
if(num == -1) num = findLocation(rightBegin, end, input, array);
return num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment