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 5 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)
52 changes: 52 additions & 0 deletions C-Plus-Plus/other/majority_vote_algorithm.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// The Boyer–Moore majority vote algorithm in C++
rutujadhanawade marked this conversation as resolved.
Show resolved Hide resolved

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

// To find majority element
int majority(int arr[], int arrsize) {
int count = 0;
for (int i = 0; i < arrsize - 1; i++) {
count = 1;
for (int j = i + 1; j < arrsize; j++) {
// Counting occurance of elements.
if (arr[j] == arr[i]) {
count++;
}
}
// checking for majority
if (count > arrsize / 2)
return arr[i];
}
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 a sequence is 1

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

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