finding majority element of an array

 #include <iostream>


int findMajority(int arr[], int n)
{
    // here the code goes
    int res = 0, count = 1;
    for (int i = 1; i < n; i++)
    {
        if (arr[res] == arr[i])
        {
            count++;
        }
        else
        {
            count--;
        }
        if (count == 0)
        {
            res = i;
            count = 1;
        }
    }
    count = 0;
    for (int i = 0; i < n; i++)
    {
        if (arr[res] == arr[i])
        {
            count++;
        }
    }
    if (count <= n / 2)
    {
        res = -1;
    }
    return res;
}

int main()
{
    // driver code goes here
    int arr[] = {3, 7, 4, 7, 7, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    std::cout << "size of the array is " << size << std::endl;
    int index = findMajority(arr, size);
    std::cout << index << std::endl;
    return 0;
}

/*
    int count = 0;
    for (int i = 0; i < n; i++)
    {
        for (int j = i; j < n; j++)
        {
            if (arr[i] == arr[j])
            {
                count++;
            }
        }
        if (count > n / 2)
        {
            return i;
        }
        else
        {
            return -1;
        }
    }*/

Post a Comment

0 Comments