-
Notifications
You must be signed in to change notification settings - Fork 3
/
61_find_majority.cpp
52 lines (44 loc) · 1.37 KB
/
61_find_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
//Write a program to find the majority element in an array (element appearing more than N/2 times).
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 10;
int arr[SIZE] = {0, 1, 1, 0, 1, 1, 1, 1, 0, 1};
int candidate = arr[0]; // Assume the first element is the majority candidate.
int count = 1; // Initialize the count of the majority candidate.
for (int i = 1; i < SIZE; ++i)
{
if (arr[i] == candidate)
{
++count; // Increment the count if the current element matches the candidate.
}
else
{
--count; // Decrement the count if the current element is different from the candidate.
}
if (count == 0)
{
candidate = arr[i]; // If count becomes zero, update the candidate.
count = 1; // Reset count to 1.
}
}
// Now 'candidate' contains the potential majority element.
int majority_count = 0; // Initialize a counter for the candidate.
for (int i = 0; i < SIZE; ++i)
{
if (arr[i] == candidate)
{
++majority_count; // Count occurrences of the candidate.
}
}
if (majority_count > SIZE / 2)
{
cout << "Majority element is: " << candidate << endl;
}
else
{
cout << "No majority element found." << endl;
}
return 0;
}