C Program to Find Majority Element in a Sorted Array

This C Program checks if a given integer X appears more than N/2 times in a sorted array of N integers.

Here is source code of the C Program to find if a given integer X appears more than N/2 times in a sorted array of N integers. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Find if a given Integer X appears more than N/2 times in a Sorted Array of N Integers
  3.  */
  4. # include <stdio.h>
  5. # define bool int
  6.  
  7. bool Morenooftimes(int array[], int n, int x)
  8. {
  9.     int i;
  10.     int final_index = n % 2 ? n / 2 : (n / 2 + 1);
  11.  
  12.     for (i = 0; i < final_index; i++)
  13.     {
  14.         /* check if x is presents more than n/2 times */
  15.         if (array[i] == x && array[i + n / 2] == x)
  16.             return 1;
  17.     }
  18.     return 0;
  19. }
  20.  
  21. int main()
  22. {
  23.     int array[] = {10, 15, 15, 12, 17 ,15};
  24.     int n = sizeof(array) / sizeof(array[0]);
  25.     int x = 15;
  26.     if (Morenooftimes(array, n, x))
  27.         printf("The given no %d appears more than %d times in array[]", x, n/2);
  28.     else
  29.         printf("The given no %d does not appear more than %d times in array[]", x, n/2);
  30.     getchar();
  31.     return 0;
  32. }

$ cc pgm95.c
$ a.out
The given no 15 appears more than 3 times in array[]

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on Arrays, go to C Programming Examples on Arrays. If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.