I am implementing effective algorithm to search last occurrence of ( the key or nearest match (upper bound)).
So far, i got this.
long bin_search_closest_match_last_occurance ( long * lArray, long sizeArray, long lnumber)
{
long left, right, mid, last_occur;
left = 0;
right = sizeArray - 1;
last_occur = -1;
while ( left <= right )
{
mid = ( left + right ) / 2;
if ( lArray[mid] == lnumber )
{
last_occur = mid;
left = mid +1;
}
if ( lArray[mid] > lnumber )
right = mid - 1;
else
left = mid + 1;
}
return last_occur!=-1?last_occur:mid;
}
Let's have an array {0,0,1,5,9,9,9,9}
and the key is 6
Fce should return index 7
, but my fce returns 4
Please note, that i do not want to iterate linearly to the last matching index.
In mind i have solution where i change parameters fce(add start,end indexes) and do another binary search withing fce from found upper bound to the end of the array (Only if i dont find exact match, last_occur==-1
).
I want to ask if there's better/cleaner solution to implement it?