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:
Any help? Thanks.
EDIT
For the given input, the majority element is shown to be 2. Which is obviously wrong.
[0, 1, 0, 1]would give no majority number, when you have actually two (unless you meantfrequency > length/2, not>=). On the other hand,[0, 1, 2, 3, 4, 5, 6, 6]would give 6 as majority number? 2) When you divide, you assume length is always even; it should beint element2 = find_majority_element(rightHalf, length/2 + (length % 2));.