Here are the details of the problem:
Given an array arr of N elements, A majority element in an array arr of size N is an element that appears more than N/2 times in the array. The task is to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true if x is a majority element (present more than n/2 times).
The solution states that the lastIndex in the loop should be conditioned.
static boolean isMajority(int arr[], int n, int x)
{
int i, last_index = 0;
/* get last index according to n (even or odd) */
last_index = (n%2==0)? n/2: n/2+1;
/* search for first occurrence of x in arr[]*/
for (i = 0; i < last_index; i++)
{
/* check if x is present and is present more
than n/2 times */
if (arr[i] == x && arr[i+n/2] == x)
return true;
}
return false;
}
I tried something else and it worked for some examples I have tried. But I am not sure whether it should really work with all cases or not.
public static boolean isMajority(int[]array,int x){
int lastIndex=array.length-(array.length/2+1);
for(int i=0;i<=lastIndex;i++){
if(array[i]==x && array[i]==array[i+array.length/2]){
return true;
}
}
return false;
}