Search code examples
c++algorithmrecursiondivide-and-conquer

Function to return count of duplicate numbers in sorted array


I want to return the number of duplicate values in a sorted array.

For example: a = { 1, 1, 2, 3, 4, 4 }, fratelli(n) should return 2. (They are 1, 1 and 4, 4)

I attempted to use a recursive approach, but it doesn't work. It Always give me 4.

I'm asking if someone please could help me understand better this methods of programming. Thanks a lot!

The function:

    #include <iostream>
    using namespace std;

    int fratelli(int a[], int l, int r)
    {
        if (l == r) return 0;
        else 
        {
            int c = (l+r) / 2;
            int n = fratelli(a, l, c) + fratelli(a, c+1, r);
            if (a[l] == a[l+1]) n++;
            return n;
        }

    }


    int main()
    {
        const int _N = 11;
        int array[_N] = { 1, 1, 2, 3, 5, 5, 7, 8, 8, 11, 12 };

        cout << "\n" << fratelli(array, 0, _N-1);


        return 0;
    } 

Solution

  • You have an error on this line:

    if (a[l] == a[l+1]) n++;
    

    The check should be at index c not at l. Apart from this your code seems alright to me.