1. c←candidate(1) 2. count←0 3.for j←1 to n 4.if A[j]=c then count←count+1 5. end for 6.if count >/2n then return c 7.elsereturn none 过程:candidate(m) 1. j←m;c←A[m];count←1 2.while j<n and count >0 3. j←j+1 4.if A[j]=c then count ←count+1 5.else count←count+1 6. end while 7.if j=n then return c 8.elsereturn candidate(j+1)
intmain() { int N; int *a; char *b; int i; printf("Please input the number of the array:\n"); scanf("%d",&N); a = (int*)malloc(N*sizeof(int)); printf("Please input the array:\n"); for (i = 0; i < N; i++) scanf("%d", &a[i]);
int x = majority(a, N); printf("%d", x); }
intmajority(int *a, int n) { int c = condidate(a, 0, n); staticint count = 0; int i; for (i = 0; i < n; i++) { if(a[i] == c) count = count + 1; } if(count > (n/2)) return c; else returnNULL; }
//一次比较的过程 intcondidate(int *a, int m, int n) { int j = m; int c = a[m]; int count = 1; while((j < n - 1)&&(count > 0)) { j = j + 1; if(a[j] == c) count = count + 1; else count = count - 1; } if(j == n - 1) return c; else return condidate(a , j+1, n); //递归调用 }