/* File: majority.c A simple recursive function to determine whether a character appears in a majority of a string. */ #include #include int count(char c, char *str, int low, int high) { if (high < low) return 0 ; if (str[high] == c) { return 1 + count(c, str, low, high-1) ; } else { return count(c, str, low, high-1) ; } } /* Return the character that appears as more than half the characters. Return 0 if no such character. */ char majority(char *str, int low, int high) { int mid, count1 = 0, count2 = 0 ; float half ; char c1, c2 ; if (high < low) return 0 ; if (low == high) return str[low] ; /* midpoint of string */ mid = (high + low) / 2 ; /* half the length,use floating point value */ half = (high - low + 1.0) / 2.0 ; c1 = majority(str, low, mid) ; c2 = majority(str, mid+1, high) ; if (c1 != 0) count1 = count(c1, str, low, high) ; if (c2 != 0) count2 = count(c2, str, low, high) ; if (count1 > half) { return c1 ; } else if (count2 > half) { return c2 ; } else { return 0 ; } } main(int argc, char *argv[]){ char c, *str ; int n ; if (argc != 2) { printf("Usage: majority str\n") ; exit(1) ; } str = argv[1] ; n = strlen(str) - 1 ; c = majority(str, 0, n) ; if (c != 0) { printf("%c is the majority character\n", c) ; } else { printf("No majority character\n") ; } }