As one of the comments mentions, Binary search is used to find an element in a sorted array which doesn't seem to be the case in your problem.
A simple divide and conquer algorithm would be to break the array into smaller parts and solve the problem on them. For example, if the input of the algorithm is the array in
and value k
, you can write a function that divide the array by two and counts the number of occurrences in each section and then adds them together.
This function takes the left
and right
values which are indices in the given vector. Initially this function is called with left=0
and right=in.size()
:
int NumberOfOccurances(const vector<int> &in, int k,
int left, int right){
// Base case when the size of the array is 1:
if(right - left==1){
return in[0] == k ? 1 : 0;
} else {
// Otherwise, break it into two subproblems.
int mid = (left + right) / 2;
return NumberOfOccurances(in, k, left, mid) +
NumberOfOccurances(in, k, mid, right)
}
}
Instead of dividing by 2, you could also divide by 3, 4, or another integer value.