Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Boyer Moore majority vote Algorithm in c++ #1730

Merged
merged 7 commits into from
Dec 30, 2020
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions C-Plus-Plus/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,4 @@ _add list here_
- [Kth smallest element](other/Kth_smallest_element.cpp)
- [Generate all Subsets](other/subsets.cpp)
- [Stock Span Problem](other/Stock_span_problem.cpp)
- [Boyer–Moore majority vote algorithm](other/majority_vote_algorithm.cpp)
59 changes: 59 additions & 0 deletions C-Plus-Plus/other/majority_vote_algorithm.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// The Boyer–Moore majority vote algorithm in C++
rutujadhanawade marked this conversation as resolved.
Show resolved Hide resolved
// This algorithm finds a majority element, if there is one: i.e, an element that occurs repeatedly for more than half of the elements of the input.

#include <bits/stdc++.h>
using namespace std;

// To find majority element
int majority(int arr[], int arrsize) {
int index = 0, count = 1;
// finding num to check majority
for (int i = 1; i < arrsize; i++) {
if (arr[index] == arr[i])
count++;
else
count--;
if (count == 0) {
index = i;
count = 1;
}
}
int num = arr[index];
for (int i = 0; i < arrsize; i++)
if (arr[i] == num)
count++;
// checking for majority
if (count > arrsize / 2)
return num;
else
return -1;
}

int main() {
int n;
cout << "Enter no of elements:";
cin >> n;
cout << "\nEnter elements: ";
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
int result = majority(arr, n);
if (result != -1)
cout << "Majority of a sequence is " << result << endl;
else
cout << "There is no majority \n";
return 0;
}

/*input/output:
Enter no of elements:5
Enter elements: 1 1 1 1 2
Majority of arr sequence is 1

Enter no of elements:5
Enter elements: 1 2 3 2 4
There is no Majority.

Time complexity : O(n)
Space complexity: O(1)
*/