3

I have a sorted String array in Java. I am trying to find the first element which starts with a user specified String in that array. I thought binary search at first, but it finds the equal String not the one which starts with the user specified String. How should I modify the binary search so that I can achieve what I want to do?

2
  • Yes, that search could/should be binary. Show us your code, searching for "ranges" is a bit complicated sometimes Commented Oct 21, 2012 at 11:42
  • I am using Arrays.binarySearch() method in standard library. Commented Oct 21, 2012 at 11:45

1 Answer 1

6

Binary search can find you the "last element which is smaller then the desired element" if the element does not exist (sometimes refered as "The index where you should insert it").

By doing binary search with this functionality you can find an element and check:

  1. If it is the exact element - then it is the first element in the array with this prefix, since it is the "smallest" element with this prefix, and you are done.
  2. If it is not the same element - by increasing one - you get the "smallest element which is bigger then the desired element". This element is the first element in the array with this prefix (if the array has one).

This functionality is very common - for example it exists in java's Arrays.binarySearch(). From the javadocs:

Returns: index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key

From the index just found, it is easy to find the desired element.

Code snap:

String[] arr = { "aa" , "bb","c", "cc" , "ccc", "cccc", "ddD" };
int idx = Arrays.binarySearch(arr, "c");
if (idx < 0) 
    System.out.println(arr[-1 * idx - 1]);
else System.out.println(arr[idx]);
Sign up to request clarification or add additional context in comments.

2 Comments

I did not know Arrays.binarySearch() could do that. Thanks for such a detailed answer.
@ipman Note I had a small problem in the original code snap (did +1 instead of -1) fixed it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.