Java Program for Check for Majority Element in a sorted array
Last Updated :
13 Dec, 2021
Question: Write a function to find if a given integer x appears more than n/2 times in a sorted array of n integers.
Basically, we need 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).
Examples:
Input: arr[] = {1, 2, 3, 3, 3, 3, 10}, x = 3
Output: True (x appears more than n/2 times in the given array)
Input: arr[] = {1, 1, 2, 4, 4, 4, 6, 6}, x = 4
Output: False (x doesn't appear more than n/2 times in the given array)
Input: arr[] = {1, 1, 1, 2, 2}, x = 1
Output: True (x appears more than n/2 times in the given array)
METHOD 1 (Using Linear Search)
Linearly search for the first occurrence of the element, once you find it (let at index i), check element at index i + n/2. If element is present at i+n/2 then return 1 else return 0.
Java
/* Program to check for majority element in a sorted array */
import java.io.*;
class Majority {
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;
}
/* Driver function to check for above functions*/
public static void main (String[] args) {
int arr[] = {1, 2, 3, 4, 4, 4, 4};
int n = arr.length;
int x = 4;
if (isMajority(arr, n, x)==true)
System.out.println(x+" appears more than "+
n/2+" times in arr[]");
else
System.out.println(x+" does not appear more than "+
n/2+" times in arr[]");
}
}
/*This article is contributed by Devesh Agrawal*/
Output:
4 appears more than 3 times in arr[]
Time Complexity: O(n)
METHOD 2 (Using Binary Search)
Use binary search methodology to find the first occurrence of the given number. The criteria for binary search is important here.
Java
/* Java Program to check for majority element in a sorted array */
import java.io.*;
class Majority {
/* If x is present in arr[low...high] then returns the index of
first occurrence of x, otherwise returns -1 */
static int _binarySearch(int arr[], int low, int high, int x)
{
if (high >= low)
{
int mid = (low + high)/2; /*low + (high - low)/2;*/
/* Check if arr[mid] is the first occurrence of x.
arr[mid] is first occurrence if x is one of the following
is true:
(i) mid == 0 and arr[mid] == x
(ii) arr[mid-1] < x and arr[mid] == x
*/
if ( (mid == 0 || x > arr[mid-1]) && (arr[mid] == x) )
return mid;
else if (x > arr[mid])
return _binarySearch(arr, (mid + 1), high, x);
else
return _binarySearch(arr, low, (mid -1), x);
}
return -1;
}
/* This function returns true if the x is present more than n/2
times in arr[] of size n */
static boolean isMajority(int arr[], int n, int x)
{
/* Find the index of first occurrence of x in arr[] */
int i = _binarySearch(arr, 0, n-1, x);
/* If element is not present at all, return false*/
if (i == -1)
return false;
/* check if the element is present more than n/2 times */
if (((i + n/2) <= (n -1)) && arr[i + n/2] == x)
return true;
else
return false;
}
/*Driver function to check for above functions*/
public static void main (String[] args) {
int arr[] = {1, 2, 3, 3, 3, 3, 10};
int n = arr.length;
int x = 3;
if (isMajority(arr, n, x)==true)
System.out.println(x + " appears more than "+
n/2 + " times in arr[]");
else
System.out.println(x + " does not appear more than " +
n/2 + " times in arr[]");
}
}
/*This code is contributed by Devesh Agrawal*/
Output:
3 appears more than 3 times in arr[]
Time Complexity: O(Logn)
Algorithmic Paradigm: Divide and Conquer
METHOD 3: If it is already given that the array is sorted and there exists a majority element, checking if a particular element is as easy as checking if the middle element of the array is the number we are checking against.
Since a majority element occurs more than n/2 times in an array, it will always be the middle element. We can use this logic to check if the given number is the majority element.
[tabby title="Java"]
java
import java.util.*;
class GFG{
static boolean isMajorityElement(int arr[], int n,
int key)
{
if (arr[n / 2] == key)
return true;
else
return false;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 3, 3, 3, 10 };
int n = arr.length;
int x = 3;
if (isMajorityElement(arr, n, x))
System.out.printf("%d appears more than %d " +
"times in arr[]", x, n / 2);
else
System.out.printf("%d does not appear more " +
"than %d times in " + "arr[]",
x, n / 2);
}
}
// This code is contributed by aashish1995
Output3 appears more than 3 times in arr[]
Time complexity: O(1)
Auxiliary Space: O(1)
Please refer complete article on
Check for Majority Element in a sorted array for more details!
Similar Reads
Java Program for Last duplicate element in a sorted array
We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Inpu
2 min read
Java Program for Ceiling in a sorted array
Given a sorted array and a value x, the ceiling of x is the smallest element in array greater than or equal to x, and the floor is the greatest element smaller than or equal to x. Assume than the array is sorted in non-decreasing order. Write efficient functions to find floor and ceiling of x. Examp
4 min read
Java Program for k-th missing element in sorted array
Given an increasing sequence a[], we need to find the K-th missing contiguous element in the increasing sequence which is not present in the sequence. If no k-th missing element is there output -1. Examples : Input : a[] = {2, 3, 5, 9, 10}; k = 1; Output : 1 Explanation: Missing Element in the incre
5 min read
Java Program to Find Largest Element in an Array
Finding the largest element in an array is a common programming task. There are multiple approaches to solve it. In this article, we will explore four practical approaches one by one to solve this in Java.Example Input/Output:Input: arr = { 1, 2, 3, 4, 5}Output: 5Input: arr = { 10, 3, 5, 7, 2, 12}Ou
4 min read
Java Program for Check if an array is sorted and rotated
Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above ar
3 min read
Java Program for Sorting all array elements except one
Given an array, a positive integer, sort the array in ascending order such that the element at index K in the unsorted array stays unmoved and all other elements are sorted. Examples: Input : arr[] = {10, 4, 11, 7, 6, 20} k = 2; Output : arr[] = {4, 6, 11, 7, 10, 20} Input : arr[] = {30, 20, 10} k =
3 min read
Java Program to Sort the Elements of an Array in Ascending Order
Here, we will sort the array in ascending order to arrange elements from smallest to largest, i.e., ascending order. So the easy solution is that we can use the Array.sort method. We can also sort the array using Bubble sort.1. Using Arrays.sort() MethodIn this example, we will use the Arrays.sort()
2 min read
Java Program to Print the Smallest Element in an Array
Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. Example: arr1[] = {2 , -1 , 9 , 10} output : -1 arr2[] = {0, -10, -13, 5} output : -13 We need to find and print the smallest value
3 min read
Java Program to Sort the Elements of an Array in Descending Order
Here, we will sort the array in descending order to arrange elements from largest to smallest. The simple solution is to use Collections.reverseOrder() method. Another way is sorting in ascending order and reversing.1. Using Collections.reverseOrder()In this example, we will use Collections.reverseO
2 min read
Java Program for Range Queries for Frequencies of array elements
Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type. Examples:  Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; l
2 min read