-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathmajority element
49 lines (42 loc) · 1.07 KB
/
majority element
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
// C++ program to find Majority
// element in an array
#include <bits/stdc++.h>
using namespace std;
// Function to find Majority element
// in an array
void findMajority(int arr[], int n)
{
int maxCount = 0;
int index = -1; // sentinels
for(int i = 0; i < n; i++)
{
int count = 0;
for(int j = 0; j < n; j++)
{
if(arr[i] == arr[j])
count++;
}
// update maxCount if count of
// current element is greater
if(count > maxCount)
{
maxCount = count;
index = i;
}
}
// if maxCount is greater than n/2
// return the corresponding element
if (maxCount > n/2)
cout << arr[index] << endl;
else
cout << "No Majority Element" << endl;
}
// Driver code
int main()
{
int arr[] = {1, 1, 2, 1, 3, 5, 1};
int n = sizeof(arr) / sizeof(arr[0]);
// Function calling
findMajority(arr, n);
return 0;
}