1 intFindsecond (intA[],intsize)2 {3 intmax = a[0];4 intSecond = A[1];5 intindex =0;6 for(inti =0; i < size; ++i)7 {8 if(Max <A[i])9 {TenSecond =Max; Oneindex =i; AMax =A[i]; - } - Else if(Max >A[i]) the { - if(Second <A[i]) - { -Second =A[i]; +index =i; - } + Else if(Second >A[i]) A { at if(Second = =max) - { -Second =A[i]; -index =i; - } - } in } - } to + returnsecond; -}
Index is the second largest number in the array subscript;
In the process of writing the algorithm, the validation found that if you remove line 21st ~ 28th Row,
When initializing Max and second equal and maximum for the entire array,
i.e. a[0] and a[1] are equal and the array is the largest,
The second largest value to be calculated will be an error.
It is found that when Max and second are initialized to be equal and the array is maximum when the above lines are removed,
The result of this algorithm will be error, the result is the maximum number.
Hereby record
Find the value of the second largest number in the shaping array