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?
Share
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:
This functionality is very common – for example it exists in java’s
Arrays.binarySearch(). From the javadocs:From the index just found, it is easy to find the desired element.
Code snap: