Skip to content

MajorElement.java #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions arrays/java/MajorElement.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/******************************************************************************
Major Element-> element having more than n/2 occurrene in an array
*******************************************************************************/
import java.util.Scanner;

public class MajorElement
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0; i<n; i++) {
arr[i]=sc.nextInt();
}
int maxElement=arr[0]; //initially let major element
int counter=1;

//check for possible major element
for(int i=1; i<n; i++) {
if(arr[i]==maxElement) {
counter++;
} else if(counter>0) {
counter--;
} else {
counter=1;
maxElement=arr[i];
}
}
int maxOccur=0;
if(counter>0) {
for(int element:arr) {
if(element==maxElement)
maxOccur++;
}
}
if(maxOccur>n/2) {
System.out.println("Major Element is: "+maxElement);
}else {
System.out.println(" No Major Element is");
}
}
}

//Input-1: 6
// 2 2 2 4 5 2
//Output-1: Major Element is: 2

//Input-2: 9
// 4 4 4 4 5 2 4 4 5
//Output-2: Major Element is: 4

//Time Complexity->O(n)