Im trying to write an algorithm to return true if a majority element exists in an array and false otherwise.
edit: i can only tell if two elements are equal. meaning i can’t use < or >, only =.
edit: the solution should be in a divide-and-conquer method.
its runtime shouldnt go over nlogn, and i wrote something in java but im not sure if it is correct and how to calculate the runtime..
here is what i got:
public static boolean MajorityBoolean(int[] arr) {
int c;
int n = arr.length;
for (int i = 0; i < n; i = i + 2) {
System.out.println("*");
if ((arr[i] == arr[(i + 1)%n]) || ((arr[i] == arr[(i - 1+n)%n]))) {
c = 0;
for (int j = 0; j < n; j = j + 1)
if (arr[j] == arr[i])
c = c + 1;
if (c > n / 2)
return true;
}
}
return false;
}
The runtime of the described algorithm is
O(n^2). The outer loop is executedn/2times, thus the inner counterjis resettedn/2times, and thus the inner loop is executed total ofO(n^2)times.I am not sure I am following the logic behind your idea, but here are two approaches how I’d implement it [in high level pseudo-code]:
(1) create a histogram out of the data:
Map<Integer,Integer>[the key is the element and the value is the number of occurances]This approach is average of
O(n)if you use aHashMapas the map.(2) sort and find max occurances:
Arrays.sort(array)for sorting.This solution is
O(nlogn)average + worst case [actually, depending on the sort – merge sort gives youO(nlogn)worst case, while quick-sort gives youO(n^2)worst case, and both areO(nlogn)on average case].EDIT:
I misunderstood the problem at hand, I thought you are looking if there is a unique maxima. These 2 solutions still fits for the problem, you just need to modify the last step of each [to check if the most occuring element appears more then half of the times, which is again fairly easy and doable in
O(n)].Also, there is another solution: Use selection algorithm to find the median, and after finding it, check if it is a majority element, and return if it is. Since selection algorithm is divide-and-conquer based solution, I think it fits your needs.