-3

I want to ckeck if all elements in an array are the same. I did it recursively, but I want to do it with divide and conquer method. Also I want that the time complexity to be O(n). How can I explain with the master theorem?

bool same_elements(int* array,size_t start, size_t end){
    if(start==end) return true;

    if(array[start]==array[start+1]){
        return same_elements(array,start+1,end);
    }
    return false;
}
Mika11
  • 9
  • 3

2 Answers2

3

Same as in your recursive scheme, if you only have an array of one element, the answer is trivially "yes".

If you have two elements, it is a "yes" if they are equal.

If you have more, pick a midpoint between start and end, recursively ensure all elements up to the midpoint are the same, and all elements from midpoint on are the same. The midpoint being checked on both sides will also ensure both sides are equal to each other.

I am not great at Master Theorem, but intuitively - counting the number of comparisons, there are zero in case of N=1, there is one in case N=2; in case of N=3, we split the problem in T(2)+T(2) = 1+1 = 2 etc. It is easy to see that there will always be exactly N-1 element comparisons.

Amadan
  • 191,408
  • 23
  • 240
  • 301
0

I tried to fix what I did. This is my code now:

bool same_elements(int* array,size_t start, size_t end){
   if(start==end) return true;

   int m = (start + end) / 2;

   if(array[m]==array[start] && array[m]==array[end]){
      return same_elements(array,start,m-1) && same_elements(array,m+1,end);
   }
   return false;
}

The time complexity is aproximately O(n).

Master Theorem:

A=2 B=2 C=0 => n^c=n^0=1

T(n)=2T(n/2) + O(1)

A>B^C => O(n^logB(A)) = O(n^log2(2)) = O(n)

Mika11
  • 9
  • 3