Majority Element in ArrayList with Divide and Conquer

#The program should return the majority element 1 but instead its returning null. Can someone please check and advise.

import java.util.ArrayList;

public class problem3  
{  
public static void main(String args[])  
{  
ArrayList\<Integer\> array = new ArrayList\<Integer\>();  
  
array.add(1);  
array.add(2);  
array.add(1);  
array.add(1);  
array.add(3);  
array.add(1);  
System.out.println("Elements of the array are: "+array);  
int low = 0, high = array.size()-1;  
problem3 obj = new problem3();  
Object result = obj.findMajority(array, low, high);  
System.out.println("The most occuring element of the array is: "+result);

}  
public Object findMajority(ArrayList\<Integer\> array, int low, int high)  
{  
// TODO Auto-generated method stub  
int n = array.size();  
int mid = (low+high)/2 ;  
if(low == high)  
{  
return array.get(low);  
}  
Object leftMajority = findMajority(array, low, mid);  
Object rightMajority = findMajority(array, mid+1, high);  
if(leftMajority == rightMajority)  
{  
return leftMajority;  
}  
int countright = 0, countleft = 0;  
for (int i=low; i\<=high;i++)  
{  
if(array.get(i) == leftMajority)  
{  
countleft++;  
}  
else if(array.get(i) == rightMajority)  
{  
countright++;  
}  
}  
if(countleft \> (int) Math.floor(n/2))  
{  
return leftMajority;  
}  
else if(countright \> (int) Math.floor(n/2))  
{  
return rightMajority;  
}  
else  
return null;  
}  
} ![console.JPG](/uploads/default/original/2X/6/682a201eb5047ae4da65d2b3086c1f06d8d9e057.jpeg)

1 Like

Hi @jaspreettoro,

This post was moved to a different board that fits your topic of discussion a bit better. This means you’ll get better engagement on your post, and it keeps our Community organized so users can more easily find information.

As you’ll notice, your Topic is now in the GitHub Programming Help and Discussion board.

1 Like

countleft and countright will never be greater than (n/2) so you always return null.

1 Like