Based on this answer to another binary search question: How can I simplify this working binary search code in C?
If you want to find the position of the first occurrence, you cannot stop when you find the corresponding element. Your search should look like this (of course, this assumes the list is sorted):
int findFirst(List<Integer> list, int valueToFind)
{
int pos=0;
int limit=list.size();
while(pos<limit)
{
int testpos = pos+((limit-pos)>>1);
if (list.get(testpos)<valueToFind)
pos=testpos+1;
else
limit=testpos;
}
if (pos < list.size() && list.get(pos)==valueToFind)
return pos;
else
return -1;
}
, . , valueToFind
, , , , ,.
.