I am working with this problem and while looking at some of posts I went got a solution with time complexity O(n) using Moore's voting algorithm . Majority element is that element which occurs more than size of array divided by 2 . For o(lg n) time following is my code please suggest whether it is in o(lg n). I welcome suggestions as I am very new to programming .
#include <bits/stdc++.h>
#include <algorithm>
using namespace std ;
int binarySearch(vector <int> a, int l, int h){
if(l - h < a.size() / 2)
return -1;
int mid = (l+h)/2;
int temporaryLow = mid;
int temporaryHigh = mid;
while(temporaryLow > 0 && a[temporaryLow] == a[mid])
temporaryLow--;
while(temporaryHigh < a.size() && a[temporaryHigh] == a[mid])
temporaryHigh++;
if((temporaryHigh -1) - (temporaryLow+1) +1 >= a.size()/2){
return a[mid];
}else{
return max(binarySearch(a,0,temporaryLow),binarySearch(a,temporaryHigh,h));
}
}
int findMajority(vector <int> numbers){
return binarySearch(numbers , 0, numbers.size());
}
int main()
{
int n ;
vector <int> a ;
while ((cin >> n) && n != 9999)
a.push_back(n);
int majority = findMajority(a);
cout << majority ;
}