Majority Element in a Array

PROGRAM

import java.util.*;

public class majority_element{

    public static void main(String args[]){

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the size: ");

        int n = sc.nextInt();

        System.out.println("Enter the elements: ");

        int a[] = new int[n];

        for(int i = 0; i<n; i++){

            a[i] = sc.nextInt();

        }

        int max = n/2;

        int k=0, c=0;

        for(int i = 0; i<n; i++){

            for(int j = 0; j<n; j++){

                if(a[i] == a[j])

                    c++;

            }

            if(c>max){

                k = a[i];

                break;

            }

        }

        System.out.println("The maximum number is : "+k);

    }

}

EXAMPLE INPUT/OUTPUT

Input:

Enter the size:
7

Enter the elements:
3 3 4 2 4 4 2

Output:

The maximum number is : 4


LOGIC

  1. The program first takes the size of the array and the elements as input from the user.

  2. It initializes the variable max to n/2 to keep track of the threshold for the majority element.

  3. Two nested loops are used to compare each element with the rest of the array.

  4. The count (c) is incremented whenever the element matches. If the count exceeds n/2, the element is stored in k as the majority element.

  5. The program prints the majority element.

Comments

Popular posts from this blog

Tic-Tac-Toe Game in Java

Trisanjit Number

Finding Subarrays with a Target Sum in Java: A Beginner's Guide