I have a function that when given a zero-indexed array A of N integers, sorted in non decreasing order, and some integer X, looks for X in A. If X is present in A, then it returns a positive index of an occurrence of X in A. Otherwise, the functions returns -1.
It should work like this:
- If I have A[0]=1, A[1]=1 and X=1 it should return 0 because A[0]=1.
But it doesn't return what I want. Can someone help me? Here is my code:
int Number(int *A, int N, int X) {
int r, m, l;
if (N == 0) {
return -1;
}
l = 0;
r = N - 1;
while (l < r) {
m = (l + r) / 2;
if (A[m] > X) {
r = m - 1;
} else {
l = m;
}
}
if (A[l] == X) {
return l;
}
return -1;
}
Binary Search does not guarantee that the found position is a first occurence of this number in an array.
It means that in this sutiation the answer "1" is correct because A[1] = 1 as well.
You need to manually iterate through the array to find the first non-matching value (or array beginning). Optimizations are possible but they are only necessary if you have an extremely big arrays with high number of value repetitions.
Also you can try a default binary search approach: