Search code examples
calgorithmdivide-and-conquer

Finding the majority element in an array using C using Divide and Conquer


Im writing an algorithm for finding a majority element in an array. Basically, if an element appears at least length/2 in an array, its a majority element. Otherwise, the array has no majority element.

Im not well versed in C, so I found the same solution in Python, and tried to convert it. However, the results I get have some unusual errors. My algorithm is this:

#include <stdio.h>
int find_majority_element(int arr[], int length);

int main()
{
    int arr[] = { 12, 3, 1, 1, 3, 4, 2, 2, 9, 6, 2, 1, 2 };
    int length = sizeof(arr)/sizeof(int);

    int result = find_majority_element(arr, length);

    if (result == -1) {
        printf("None");
    } else {
        printf("%d", result);
    }
    return 0;
}

int find_majority_element(int arr[], int length) {

    if (length == 2) {
        if (arr[0] == arr[1]) {
            return arr[0];
        } else {
            return -1;
        }
    } else if (length == 1) {
        return arr[0];
    }

    int *leftHalf = arr;
    int *rightHalf = arr + length/2;

    int element1 = find_majority_element(leftHalf, length/2);
    int element2 = find_majority_element(rightHalf, length/2);

    if (element1 == -1 && element2 >= 0) {
        return element2;
    } else if (element2 == -1 && element1 >= 0) {
        return element1;   
    }

    if (element1 == element2) {
        return element1;
    } else {
        return -1;
    }

}

This gives me unexpected results, which is weird considering the fact that I just converted another algorithm. The algorithm in question can be found here:

Link

Any help? Thanks.

EDIT

For the given input, the majority element is shown to be 2. Which is obviously wrong.


Solution

  • Code is not checking the entire right half when length is odd. @jdehesa

    // int element2 = find_majority_element(rightHalf, length/2);
    int element2 = find_majority_element(rightHalf, length - length/2);
    

    OP's approach, overall, is incorrect for an unsorted array @Dagan. Review Majority Element for alternate solutions.


    Pedantic corner: code has trouble with length <= 0.