Majority Element in Array

Majority Element in Array

Majority Element in array in Java Language

In this page, we will look into a coding question where we will learn how to find the element which occurs the majority number of times in an array in Java Programming Language.
There might be a different approach to solve this question, If you have a different approach comment below in the comment section.

Problem Statement:

Write a program in Java programming language where you need to find the element of array which occurs most time in the array.

Example:

Input
8
11 22 33 44 55 66 77 44

Output
44

ALGORITHM:

  1. Create a variable to store the max count, count = 0
  2. Traverse through the array from start to end.
  3. For every element in the array run another loop to find the count of similar elements in the given array.
  4. If the count is greater than the max count update the max count and store the index in another variable.
  5. If the maximum count is greater than the half the size of the array, print the element. Else print there is no majority element.

JAVA CODE:

// Java program to find Majority
// element in an array
import java.io.*;

class prepinsta {

    static void findmajority(int arr[], int n)
    {
        int maxCount = 0;
        int index = –1
        for (int i = 0; i < n; i++) {
            int count = 0;
            for (int j = 0; j < n; j++) {
                if (arr[i] == arr[j])
                    count++;
            }
            if (count > maxCount) {
                maxCount = count;
                index = i;
            }
        }

        
        if (maxCount > n / 2)
            System.out.println(arr[index]);

        else
            System.out.println(“No Majority Element”);
    }

    
    public static void main(String[] args)
    {

        int arr[] = { 2121252 };
        int n = arr.length;

        // Function calling
        findmajority(arr, n);
    }
    
}
Output:

2