Advertisement
Guest User

Untitled

a guest
May 25th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int findCandidate(int *, int);
  4. int isMajority(int *, int, int);
  5.  
  6. int main() {
  7.     int arr[] = {34,15,34,34,34,34,15,15,34,34,22,15,15,15,15,34,15,34,15,15,34,15,34,15,34,22,22,15,34,15,34,15,34,15,34,22,34,22,34,34,34,34,34,22,15,34,34,34,15,34,15,15,22,34,15,15,34,34,34,22,34,15,15,34,34,34,15,22,22,22,15,34,34,22,34,34,22,34,15,22,34,34,15,22,34,34,34,34,22,22,15,34,34,22,34,34,34,22,34,22};
  8.     int size = sizeof(arr)/sizeof(int);
  9.     int candidate = findCandidate(arr, size);
  10.     int majority = isMajority(arr, size, candidate);
  11.     printf("size: %d, candidate: %d, majority: %d", size, candidate, majority);
  12.     return 0;
  13. }
  14.  
  15. int findCandidate(int * arr, int size) {
  16.     int majIdx = 0, count = 1, i;
  17.     for(i = 1; i < size; i++) {
  18.         if (count == 0) {
  19.             majIdx = i;
  20.             count = 1;
  21.             continue;
  22.         }
  23.  
  24.         if (arr[majIdx] == arr[i])
  25.             count++;
  26.         else
  27.             count--;
  28.     }
  29.  
  30.     if(count == 0)
  31.         return -1;
  32.  
  33.     return arr[majIdx];
  34. }
  35.  
  36. int isMajority(int * arr, int size, int candidate) {
  37.     int i, count = 0;
  38.     for(i = 0; i < size; i++) {
  39.         if(arr[i] == candidate)
  40.             count++;
  41.     }
  42.  
  43.     if(count > size/2)
  44.         return 1;
  45.  
  46.     return 0;
  47.  
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement