fork(3) download
  1. # include<stdio.h>
  2. # define bool int
  3.  
  4. int findCandidate(int *, int);
  5. bool isMajority(int *, int, int);
  6.  
  7. void printMajority(int a[], int size)
  8. {
  9. int cand = findCandidate(a, size);
  10.  
  11. if(isMajority(a, size, cand))
  12. printf(" %d ", cand);
  13. else
  14. printf("NO Majority Element");
  15. }
  16.  
  17. int findCandidate(int a[], int size)
  18. {
  19. int maj_index = 0, count = 1;
  20. int i;
  21. for(i = 1; i < size; i++)
  22. {
  23. if(a[maj_index] == a[i])
  24. count++;
  25. else
  26. count--;
  27. if(count == 0)
  28. {
  29. maj_index = i;
  30. count = 1;
  31. }
  32. }
  33. return a[maj_index];
  34. }
  35.  
  36. bool isMajority(int a[], int size, int cand)
  37. {
  38. int i, count = 0;
  39. for (i = 0; i < size; i++)
  40. if(a[i] == cand)
  41. count++;
  42. if (count > size/2)
  43. return 1;
  44. else
  45. return 0;
  46. }
  47.  
  48. int main()
  49. {
  50. int a[] = {1, 3, 3, 1,1,1,2,3,1,2,1,1};
  51. printMajority(a, 12);
  52. getchar();
  53. return 0;
  54. }
Success #stdin #stdout 0.01s 2728KB
stdin
Standard input is empty
stdout
 1