Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

****** In JAVA ************ Given an array of integers A, find the Majority Elem

ID: 3886685 • Letter: #

Question

****** In JAVA ************

Given an array of integers A, find the Majority Element.

Majority Element in an array of size N in an element that appears more than N/2 times.

Write a function:
        int findMajority(int[] A)

that accepts an array A. The function should return the Majority Element in the array. If no majority element then return 0.

Use following methods to solve the problem:

int findCandidate(int a[])

that accepts the array and find a candidate for the majority

boolean isMajority(int a[], int cand)

that accept the array and the candidate element and check if the candidate occurs more than n/2 times

Input
    5
    1 2 1 2 2

    Where,

First line represents the size of an array.

Second line represents array elements separated by single space.

Output
    2

Here for the given array, 2 appears 3 times in the array of size 5.

No space after the element in the output.

Assume that,

N is an integer within the range [1 to 10000].

Array elements are within the range [-2147483648 to 2147483647].

Explanation / Answer

FindCandidateTest.java

import java.util.Scanner;

public class FindCandidateTest {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

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

int n = scan.nextInt();

int a[] = new int[n];

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

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

a[i] = scan.nextInt();

}

FindCandidateTest obj = new FindCandidateTest();

System.out.println("Output: "+obj.findCandidate(a));

}

int findCandidate(int a[]) {

for(int i=0;i<a.length;i++){

if(isMajority(a, a[i])) {

return a[i];

}

}

return -1;

}

boolean isMajority(int a[], int cand) {

int count = 0;

for(int i=0;i<a.length;i++){

if(a[i] == cand) {

count++;

}

}

if(count > a.length/2){

return true;

}

return false;

}

}

Output:

Enter the size of an array:
5
Enter the array elements:
1 2 1 2 2
Output: 2