forked from ZoranPandovski/al-go-rithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Boyer-Moore Majority Voting Algorithm
- Loading branch information
1 parent
bcf67bc
commit 30afdbc
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
//Boyer-Moore Majority Voting Algorithm | ||
|
||
#include <iostream> | ||
using namespace std; | ||
// Function to find majority element | ||
int findMajority(int arr[], int n) | ||
{ | ||
int i, candidate = -1, votes = 0; | ||
// Finding majority candidate | ||
for (i = 0; i < n; i++) { | ||
if (votes == 0) { | ||
candidate = arr[i]; | ||
votes = 1; | ||
} | ||
else { | ||
if (arr[i] == candidate) | ||
votes++; | ||
else | ||
votes--; | ||
} | ||
} | ||
int count = 0; | ||
// Checking if majority candidate occurs more than n/2 | ||
// times | ||
for (i = 0; i < n; i++) { | ||
if (arr[i] == candidate) | ||
count++; | ||
} | ||
|
||
if (count > n / 2) | ||
return candidate; | ||
return -1; | ||
} | ||
int main() | ||
{ | ||
int arr[] = { 1, 1, 1, 1, 2, 3, 4 }; | ||
int n = sizeof(arr) / sizeof(arr[0]); | ||
int majority = findMajority(arr, n); | ||
cout << " The majority element is : " << majority; | ||
return 0; | ||
} | ||
|
||
/* | ||
Time Complexity: O(n) ( For two passes over the array ) | ||
Space Complexity: O(1) | ||
*/ |