Reputation: 2025
I would like to do the following in Java: I have an element, and I would like to know what would be its index had it been inserted into a collection of other objects (given they're already sorted).
So if I have a vector of ints like this: 1,3,5,7,9 and I had the int '2' in hand, I'd know that its 'would-be' index is i=1, between values 1 and 3.
Upvotes: 2
Views: 1314
Reputation: 80340
// assumes vector is sorted
// and that vector does not yet contain searchedObject
insertionPoint = -1 * Collections.binarySearch(vector,searchedObject) - 1;
Definition of Collections.binarySearch() states
Returns:
index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
Upvotes: 5