-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajority_element.cpp
More file actions
56 lines (42 loc) · 1.15 KB
/
majority_element.cpp
File metadata and controls
56 lines (42 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// The following program is written in c++ and it finds the majority element in the array which have frequency of greater than the value
// n/2 , where n is the size of the taken array
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int counter;
int maxCount=0;
int index;
int major;
int arr[n];
for(int i=0 ; i<=n-1 ;i++)
{
cin>>arr[i];
}
for(int i = 0 ; i<=n-1 ; i++)
{
for(int j = 0 ; j<=n-1;j++)
{
if(arr[i] == arr[j])
{
// major = arr[i];
counter++;
}
}
if(counter > maxCount)
{
maxCount = counter;
index = i;
}
}
if(counter > n/2)
{
cout<<arr[index]<<endl;
}
else
{
cout<<"-1"<<endl;
}
return 0 ;
}