views:

66

answers:

1

Hello, 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.

+5  A: 
// 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.

Peter Knego
Note that binarySearch() returns "(-(insertion point) - 1)" in the case that the object does not exist in the list. This means you'll have to add 1 to the return value and negate it to find the insertion point. http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20T%29
fizban
I should point out that the vector is sorted in an ascending order. Will this mean the behavior is still the same or do I have to count for that as well?
Voulnet
Thanks. I corrected the post. I rushed to achieve first post ;)
Peter Knego
Yes it is supposed to be in the ascending order. If you have a custom order, you must pass the comparator to binarySearch(): http://download.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html#binarySearch(java.util.List,%20T,%20java.util.Comparator
Peter Knego