Let T [0: n-1] Be an array of n elements. For any element x, set S (x) = {I | T [I] = x }. When | S (x) |> n/2, X is the primary element of T. Design an algorithm to determine whether T [0: n-1] has a primary element. The algorithm is described as follows: A1 A2 A3 A4... AJ + 1... ... An first writes A1 to m, and the counter K is set to 1. Then let m compare A1, A2 ..., If it is the same as M, K adds 1. If it is different, K minus 1. In this case, K = 0 may be compared When AJ is compared. Then, AJ + 1 is retrieved and saved to m, and K is set to 1. Repeat the preceding operation to check all the elements in a [1: N. After this process is completed, K has two possible values: ① K = 0, ② K> 0. When K = 0, a [0: n-1] must have no primary element. When K> 0, a [0: n-1] may have a primary element or no primary element. If a [0: n-1] has a primary element, the m value must be the primary element. Obviously, compare all the elements of m with a [0: n-1], that is, whether M is the primary element of a [0: n-1], that is, a [0: n-1: n-1] whether the primary element exists. The algorithm is as follows:
Template <class T> void mainmember (t a [], int N) {int I, J, K, M; M = A [0]; k = 1; j = 0; for (I = 1; I <n; I ++) {If (M = A [I]) K ++; else k --; if (k = 0) {I ++; if (I> N) break; // the elements in a [0: n-1] have been compared, jump out of M = [I];
K = 1 ;}} if (k = 0) cout <"array A has no primary element! "<Endl; else {for (I = 0; I <n; I ++) if (M = A [I]) J ++ ;} if (j> n/2) cout <"array A contains the primary element. The primary element is:" <m <Endl; else cout <"array A does not contain the primary element! "<Endl ;}
Determine whether T [0: N] has a primary element in linear time.