-2

Me and Friend were discussing if we can count how many a certain Element k appears in the array A[1....n] using Divide and Conquer algorithm without sorting the Array?

We reached a Blockade that if we use Binary search it will stop once it finds the element once. Any Ideas?

1 Answers1

-2

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.

Ari
  • 7,251
  • 11
  • 40
  • 70