#include #include #include #define N 100 #define M 5 /* Random string of length n over an alphabet of size m */ char *genarr ( int n, int m ) { int i, t, r; char *A; A = (char *)malloc((n+1)*sizeof(char)); A[n] = '\0'; t = rand() % m; /* The character that is going to have frequency about n/2 */ for (i=0; i n / 2) return A[n-1]; /* If not, forget the last element */ --n; } /* Prepare the array for the recursive call */ B = (char *)malloc((n/2+1)*sizeof(char)); j = 0; for (i=0; i n / 2) return x; return (char)(-1); } /* For printing diagnostic messages */ void diagnostic ( char *A, int n, int m ) { int i; for (i=0; i= 3) { n = atoi(argv[1]); m = atoi(argv[2]); } else { n = N; m = M; } srand((unsigned int)time(NULL)); A = genarr(n,m); x = findmaj(A,n); if (x == (char)(-1)) { printf("No majority element exists\n"); diagnostic(A,n,m); } else { printf("Majority element is %c with frequency %d\n", x, findfreq(A,n,x)); } free(A); exit(0); }