-
Notifications
You must be signed in to change notification settings - Fork 3
/
majority.cpp
60 lines (46 loc) · 1.13 KB
/
majority.cpp
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
57
58
59
60
#include <iostream>
using namespace std;
int Majorityfunc(int arr[], int n) {
int majority = arr[0];
int count = 1;
// Find the potential majority element
for (int i = 1; i < n; ++i) {
if (arr[i] == majority) {
count++;
} else {
count--;
if (count == 0) {
majority = arr[i];
count = 1;
}
}
}
// Verify if the potential majority element is the actual majority
count = 0;
for (int i = 0; i < n; ++i) {
if (arr[i] == majority) {
count++;
}
}
if (count > n / 2) {
return majority;
}
return -1; // No majority element found
}
int main() {
int n;
cout<<"Enter the number of elements : \n";
cin>>n;
int arr[n];
for(int i = 0 ; i<n; i++){
cout<<"\nEnter "<<i+1<<" Number : ";
cin>>arr[i];
}
int majority = Majorityfunc(arr, n);
if (majority != -1) {
cout << "\nMajority element is: " << majority << "\n\n\n";
} else {
cout << "\nNo majority element found." << "\n\n\n";
}
return 0;
}