Skip to content

Instantly share code, notes, and snippets.

@ravichandrae
Created October 13, 2013 02:30
Show Gist options
  • Save ravichandrae/6957431 to your computer and use it in GitHub Desktop.
Save ravichandrae/6957431 to your computer and use it in GitHub Desktop.
This java program implements the moore's voting algorithm to find the majority number ( which appears in more than half) in the array
public class Main {
public static void main(String[] args)
{
int [] array = {6,2,3,6,3,6,6,6};
System.out.println("Majority number is: " + getMajorityNum(array));
}
public static int getMajorityNum(int[] array)
{
//Initialize first num as majority num
int majorNum = array[0];
int count = 1;
for( int i = 1; i < array.length; i++ )
{
if( array[i] == majorNum )
{
count++;
}
else
{
count--;
if( count == 0) //reset the majority number if count reaches 0
{
count = 1;
majorNum = array[i];
}
}
}
count = 0;
for( int i = 0; i < array.length; i++ )
{
if( array[i] == majorNum )
{
count++;
}
}
return majorNum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment