Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
C Program to Sort the Elements of an Array in Descending Order
Next article icon

C Program to Check for Majority Element in a sorted array

Last Updated : 31 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. 
 

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.

C
/* C Program to check for majority element in a sorted array */ # include <stdio.h> # include <stdbool.h>  bool isMajority(int arr[], int n, int x) {     int i;      /* get last index according to n (even or odd) */     int last_index = n%2? (n/2+1): (n/2);      /* 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 1;     }     return 0; }  /* Driver program to check above function */ int main() {      int arr[] ={1, 2, 3, 4, 4, 4, 4};      int n = sizeof(arr)/sizeof(arr[0]);      int x = 4;      if (isMajority(arr, n, x))         printf("%d appears more than %d times in arr[]",                x, n/2);      else         printf("%d does not appear more than %d times in arr[]",                 x, n/2);     return 0; } 

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. 

C
/* C Program to check for majority element in a sorted array */ # include <stdio.h> # include <stdbool.h>  /* If x is present in arr[low...high] then returns the index of first occurrence of x, otherwise returns -1 */ int _binarySearch(int arr[], int low, int high, int x);  /* This function returns true if the x is present more than n/2 times in arr[] of size n */ bool 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; }  /* If x is present in arr[low...high] then returns the index of first occurrence of x, otherwise returns -1 */ 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; }  /* Driver program to check above functions */ int main() {     int arr[] = {1, 2, 3, 3, 3, 3, 10};     int n = sizeof(arr)/sizeof(arr[0]);     int x = 3;     if (isMajority(arr, n, x))         printf("%d appears more than %d times in arr[]",                x, n/2);     else         printf("%d does not appear more than %d times in arr[]",                x, n/2);     return 0; } 

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.

C] [tabby title=C
#include <stdio.h> #include <stdbool.h>    bool isMajorityElement(int arr[], int n, int key) {     if (arr[n / 2] == key)         return true;     else         return false; }  int main() {     int arr[] = { 1, 2, 3, 3, 3, 3, 10 };     int n = sizeof(arr) / sizeof(arr[0]);     int x = 3;     if (isMajorityElement(arr, n, x))         printf("%d appears more than %d times in arr[]", x,             n / 2);     else         printf("%d does not appear more than %d times in "             "arr[]",             x, n / 2);     return 0; } 

Output
3 appears more than 3 times in arr[]

Time complexity: O(1)
Auxiliary Space: O(1)

Algorithm

  1. Initialize a variable candidate to the first element of the input array nums, and a variable count to 1.
  2. Loop through the elements of the input array nums starting from the second element.
  3. If the current element is equal to the candidate, increment count by 1.
  4. If the current element is not equal to the candidate, decrement count by 1. If count becomes 0, set the candidate to the current element and set count to 1.
  5. After the loop, loop through the elements of the input array nums again, counting how many times the candidate appears.
  6. If the count of the candidate is greater than n/2 where n is the size of the input array nums, return the candidate as the majority element.
  7. Otherwise, return -1 to indicate that there is no majority element.
C
#include <stdio.h>  int findMajorityElement(int* nums, int n) {     int candidate = nums[0], count = 1;          for (int i = 1; i < n; i++) {         if (nums[i] == candidate) {             count++;         } else {             count--;             if (count == 0) {                 candidate = nums[i];                 count = 1;             }         }     }          count = 0;     for (int i = 0; i < n; i++) {         if (nums[i] == candidate) {             count++;         }     }          if (count > n/2) {         return candidate;     } else {         return -1;  // no majority element     } }  int main() {     int nums[] = {1, 2, 3, 4, 4, 4, 4};     int n = sizeof(nums)/sizeof(nums[0]);     int majority = findMajorityElement(nums, n);          if (majority != -1) {         printf("The majority element is %d\n", majority);     } else {         printf("There is no majority element\n");     }          return 0; } 

Output
The majority element is 4 

The time complexity is O(n), and the auxiliary space  is O(1)

Please refer complete article on Check for Majority Element in a sorted array for more details!


Next Article
C Program to Sort the Elements of an Array in Descending Order
author
kartik
Improve
Article Tags :
  • Divide and Conquer
  • C Programs
  • C Language
  • DSA
  • Arrays
  • Binary Search
Practice Tags :
  • Arrays
  • Binary Search
  • Divide and Conquer

Similar Reads

  • C 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
  • C Program to Find Largest Element in an Array
    In this article, we will learn how to find the largest element in the array using a C program. The simplest method to find the largest element in the array is by iterating the array and comparing each element with the assumed maximum and updating it when the element is greater. [GFGTABS] C #include
    3 min read
  • C Program to Sort the Elements of an Array in Descending Order
    Sort an array in descending order means arranging the elements in such a way that the largest element at first place, second largest at second place and so on. In this article, we will learn different ways to sort an array in descending order in C. The simplest method to sort the array in descending
    3 min read
  • C program to count frequency of each element in an array
    Given an array arr[] of size N, the task is to find the frequency of each distinct element present in the given array. Examples: Input: arr[] = { 1, 100000000, 3, 100000000, 3 } Output: { 1 : 1, 3 : 2, 100000000 : 2 } Explanation: Distinct elements of the given array are { 1, 100000000, 3 } Frequenc
    4 min read
  • C Program to Sort an Array in Ascending Order
    Sorting an array in ascending order means arranging the elements in the order from smallest element to largest element. The easiest way to sort an array in C is by using qsort() function. This function needs a comparator to know how to compare the values of the array. Let's look at a simple example:
    3 min read
  • C Program to Find the Maximum and Minimum Element in the Array
    In this article, we will discuss different ways to find the maximum and minimum elements of the array in C. The simplest method to find the maximum and minimum element of the array is iterates through the array and compare each element with the assumed minimum and maximum and update them if the curr
    3 min read
  • C Program for Search an element in a sorted and rotated array
    An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time.  Exam
    4 min read
  • C/C++ Program for Odd-Even Sort / Brick Sort
    This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in
    2 min read
  • C Program to Remove Duplicates from Sorted Array
    In this article, we will learn how to remove duplicates from a sorted array using the C program. The most straightforward method is to use the two-pointer approach which uses two pointers: one pointer to iterate over the array and other to track duplicate elements. In sorted arrays, duplicates are a
    4 min read
  • C program to sort an array using pointers
    Given an array of size n, the task is to sort this array using pointers in C. Examples: Input: n = 5, arr[] = {0, 23, 14, 12, 9} Output: {0, 9, 12, 14, 23} Input: n = 3, arr[] = {7, 0, 2} Output: {0, 2, 7} Approach: The array can be fetched with the help of pointers with the pointer variable pointin
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences