Search code examples
javaboyer-moore

Program to find majority element of an input array doesn't work


I'm trying to find the majority element using Boyer and Moore approach. The program should ask the user to input "n" number of lines on the first line, then there will be "n" numbers followed "n" lines as input. (Ex: user input 5 on the first line, then there will be 5 numbers followed) Next, use Boyer and Moore approach to find the majority element of an input array. If the majority element doesn't exist in the input array, then execute -1. My program output shows 0 no matter what input I entered. Would you please check it and correct my program?

Output example: 4 12 12 1 12 12 /Or: 3 11 2 13 -1

public static void main (String[]args)
{
    int a[] = new int [1000000];
    Scanner sc = new Scanner (System.in);

    // User input n number of lines
    int numberOfLine = sc.nextInt();

    //Loop to have n elements as input
    for (int i = 1; i<= numberOfLine; i++)
    {
        a[i] = sc.nextInt();
    }

    // Call method to display majority element
    getMajorityElement(a);
    sc.close();
}       

//Method to Find M.E using Boyer & Moore approach
public static void getMajorityElement(int [] array)
{
    int majorityElement = array[0];
    int count = 1;
    for (int index = 1; index<array.length; index++)
    {
        if(majorityElement==array[index])
        {
            count++;
        }
        else if(count==0)
        {
            majorityElement = array[index];
            count = 1;
        }
        else 
        {
            count --;
        }
    }

    // Check if candidate M.E occur more than n/2 times
    count = 0;
    for (int index = 0; index<array.length; index++)
    {
        if(array[index]==majorityElement)
            {
            count++;
            }
    }
        if (count > array.length/2)
        {
        System.out.println(majorityElement);
        }
        else
        {
        System.out.println("-1");
        }
}

Solution

  • The reason you get this behavior is that your array of 1,000,000 elements has a majority element of zero: only the initial three or four items are set, while the rest of the items are occupied by zeros - the default value of an int in Java.

    Fix this problem by allocating at size once the length is entered. You also need to fix the code that reads input to make sure that the data ends up at indexes 0..numberOfLine-1:

    Scanner sc = new Scanner (System.in);
    // User input n number of lines
    int numberOfLine = sc.nextInt();
    int a[] = new int [numberOfLine];
    //Loop to have n elements as input
    for (int i = 0 ; i < numberOfLine ; i++) {
        a[i] = sc.nextInt();
    }