Since you want to implement it yourself, Collections.binarySearch isnt good enough for you?
Okay....
Binary Search:
you have a sorted list. Get the element in the middle and compare with the Object in question. if it is lower than the element you want to find, repeat the search in the part of the list, which has only higher elements. If it is higher, search in the list part with only lower elements.
So how do you do binary search?
You need a measure, which defines for 2 object what the lower one and what the higher one is.
Your object must implement Comparable or you must define a Comparator for your list.
Then you need to actually sort the list. Sorting would be Collections.sort(myList).
Now List has the size() method, which will help you determine the first "middle" element.
Pseudocode :
**input** : keyElement
startIndex = 0;
endIndex = list.size();
midIndex = (endIndex+startIndex) / 2;
while(list.get(midIndex) != keyElement) {
if (list.get(midIndex) < keyElement) {
startIndex = midIndex;
} else {
endIndex = midIndex;
}
midIndex = (endIndex+startIndex) / 2;
}
return midIndex;
Something along those lines (be careful with boundaries here... maybe a +/-1 is needed.)