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

Create majority_element.cpp #237

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all 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
40 changes: 40 additions & 0 deletions C++ program/majority_element.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Author : Divyansh Rai
// C++ program to find Majority element in an array
#include <bits/stdc++.h>
using namespace std;

// Function to find Majority element in an array it returns -1 if there is no majority element

int majorityElement(int *arr, int n)
{
if (n == 1) return arr[0];

int cnt = 1;
// sort the array, o(nlogn)
sort(arr, arr + n);
for (int i = 1; i <= n; i++){
if (arr[i - 1] == arr[i]){
cnt++;
}
else{
if (cnt > n / 2){
return arr[i - 1];
}
cnt = 1;
}
}
// if no majority element, return -1
return -1;
}



int main()
{ int n;
cin>>n;
int arr[n] ;
for(int &x:arr)cin>>x;
cout<<majorityElement(arr, n);

return 0;
}