On trying to find the majority element I came up with this code. But the expected output is not printed. What is wrong with this code. Plz Help!!!!!!
Input : {3, 3, 4, 2, 4, 4, 2, 4, 4} Output : 4 Explanation: The frequency of 4 is 5 which is greater than half of the size of the array size.
Input : {3, 3, 4, 2, 4, 4, 2, 4} Output : No Majority Element Explanation: There is no element whose frequency is greater than half of the size of the array size.
#include <iostream>
using namespace std;
int main()
{
int i,count = 1 , max = 0,n;
cin >> n;
int a[n];
for(i=0 ; i<n ; i++) {
cin >> a[n];
}
for(i = 1 ; i<n ; i++) {
if(a[max] == a[i]){
count += 1;
}
else {
count -= 1;
}
if(count == 0){
max = i;
count =1;
}
}
if(count > n / 2) {
cout << a[max];
}
else {
cout<<"No Max Element";
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire