Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - 1. Design a sorting algorithm for integer array A[n]. 2. Find the maximum value and the second maximum value of the elements in integer array A[n].
1. Design a sorting algorithm for integer array A[n]. 2. Find the maximum value and the second maximum value of the elements in integer array A[n].
First, the c++ algorithm library provides sorting functions to support sorting. And the rapid scheduling is realized.

Just sort it directly. For the largest and second largest, it can be achieved by scanning at the same time. Record two pointers. Max 1, max2. Keep the current position as the second largest. Then just update it when scanning. But if the sequence is finished, the largest and second largest are A[N] and A[N- 1].

(ps: If it is the second largest in the strict sense, it still needs to be scanned again, or the data is not too large, you can use counting sort or record C[I] to indicate how many times the number I appears, and then scan the C array from small to large. See the number I output several times)

Code: (sorting implementation):

# include & ltiostream & gt

# include & lt algorithm & gt

# include & ltcstdio & gt

Use namespace std

const int Maxn = 1000000;

Static int n, m;

Static int a [maxn];

int main()

{

scanf("%d ",& ampn);

for(int I = 1; I < = n; i++)

scanf("%d ",& ampa[I]);

sort(A+ 1,A+n+ 1);

printf("%d %d\n ",A[n],A[n- 1]);

Returns 0;

}