Skip to content

Instantly share code, notes, and snippets.

@SuryaPratapK
Created January 27, 2020 17:54
Show Gist options
  • Save SuryaPratapK/99aeb7ef3e0c2a6797aff9b869232777 to your computer and use it in GitHub Desktop.
Save SuryaPratapK/99aeb7ef3e0c2a6797aff9b869232777 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
void findMajority(int arr[], int n)
{
// Number of bits in the integer
int len = sizeof(int) * 8;
// Variable to calculate majority element
int number = 0;
// Loop to iterate through all the bits of number
for (int i = 0; i < len; i++) {
int count = 0;
// Loop to iterate through all elements in array
// to count the total set bit
// at position i from right
for (int j = 0; j < n; j++) {
if (arr[j] & (1 << i))
count++;
}
// If the total set bits exceeds n/2,
// this bit should be present in majority Element.
if (count > (n / 2))
number += (1 << i);
}
int count = 0;
// iterate through array get
// the count of candidate majority element
for (int i = 0; i < n; i++)
if (arr[i] == number)
count++;
// Verify if the count exceeds n/2
if (count > (n / 2))
cout << number;
else
cout << "Majority Element Not Present";
}
// Driver Program
int main()
{
int arr[] = { 3, 3, 4, 2, 4, 4, 2, 4, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
findMajority(arr, n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment