Title: Implement a function to find the second largest number in an array of integers.
Algorithm idea:
Set two variables max1 and MAX2 to hold the largest and second largest numbers, and then compare the remaining number of the array to these two numbers sequentially, if the number a is larger than Max1, first assign max1 to Max2 so that the largest number is the second biggest number, and then assign the number A to Max1, If the number a is smaller than max1 but larger than MAX2, assign this number A to max2, and so on, until the number in the array is compared.
C Language code:
1#include <stdio.h>2#include <stdlib.h>3 #defineN 104 voidProduce_random_array (intArray[],intn);5 voidShow_array (intArray[],intn);6 intSearch_second_max (intArray[],intn);7 intMainintAGRC,Char*agrv[])8 {9 intArray[n];Ten Produce_random_array (array, N); Oneprintf"The original array is as follows: \ n"); A Show_array (array, N); -printf"\nthe Second_max is:%d\n", Search_second_max (array, N)); -System"Pause"); the return 0; - } - voidProduce_random_array (intArray[],intN) - { + inti; - Srand (Time (NULL)); + for(i =0; I < n; i++) A { atArray[i] = rand ()% -; - } - } - voidShow_array (intArray[],intN) - { - inti; in for(i =0; I < n; i++) -printf"%-3d", Array[i]); to } + intSearch_second_max (intArray[],intN) - { the intmax1, Max2, I; *MAX1 = array[0]; $ for(i =1; I < n; i++)Panax Notoginseng { - if(array[i]>max1) the { +MAX2 =max1; AMax1 =Array[i]; the } + Else - { $ if(i = =1) $MAX2 =Array[i]; - Else if(array[i]>max2) -MAX2 =Array[i]; the } - }Wuyi returnMax2; the}
C Language Classic algorithm--find the second largest number in an array of integers