Efficient Java Function to retrieve ID from ordered array
In a Java program, I have an array of objects. Each object has a field that is an ID number and all fields are public (no getters and setters). The array is ordered by ID number which is an integer. I don't want to use a for loop or a similar technique to loop through every object because the array may be large. So,
开发者_StackOverflow社区- what search algorithm will do this efficiently, and...
- is there a handy Java method that will do this search for me so I don't have to write it myself?
Either use java.util.Arrays.binarySearch() (if its an array of primitives or you have a Comparator) or java.util.Collections.binarySearch() (if you have a non-array collection of your own Comparable object).
It sounds like Arrays.binarySearch would fit your problem better. Write a proper java.util.Comparator that understands your ordering.
What search algorithm
Binary search.
Is there a function to do it?
Yes, binarySearch in java.util.Arrays
The only catch is you will need to write a Comparator
that extracts the id
field. Something like, if you had a class
static class A {
int id;
A(int _id) { this.id = _id; }
}
it could look like
Comparator<A> idComp = new Comparator<A>() {
public int compare(A a1, A a2) {
return new Integer(a1.id).compareTo(a2.id);
}
public boolean equals(A a1, A a2) {
return a1.id == a2.id;
}
};
One way to do it, is take your order array, and search it like a binary tree. Start at the middle, if the number you are looking for is greater than queried, repeat in the 1/2 - 3/4 - 1 section, if it is less than, repeat in the 0 - 1/4 - 1/2 section.
Make it recursive, and take in the array subset. On the first call, it will be the entire array, on the second, it will either be the higher or lower ID half, and on the third call, it will effectively be one fourth of the original... and so on.
精彩评论