[My C language interview series] 012 find the second largest number in the integer Array
Find the second largest number in the integer Array
Question: Write a function to find the second largest number in an integer array. [Mirosoft]
PS: 1, "66,66, 66,66, 66", there is no second largest number.
2. "99,99, 88,86, 68,66", the maximum number is 88.
Next I will first show the program for finding the maximum number:
Int getfirstmaxnumber (INT buffer [])
{
Int I, Max;
Max = buffer [0];
For (I = 1; I <arrsize; I ++)
{
If (buffer [I]> MAX)
Max = buffer [I];
}
Return Max;
}
This algorithm is very classic and time complexity is: O (n ). To find the maximum number in an array, we must at least scan the array, if you can solve the problem by scanning the array only once, the algorithm is already a good algorithm.
The algorithm for finding the second largest number is implemented based on the algorithm for finding the maximum number. The program for finding the second largest number is given below:
# Define arrsize 10
# Define minnumber 0 xffffffff
# Define find_sucess 1
# Define find_fail 0
Int getsecondmaxnumber (INT buffer [], int * secondmax)
{
Int I, Max;
Max = buffer [0];
* Secondmax = minnumber;
For (I = 1; I <arrsize; I ++)
{
If (buffer [I]> MAX)
{
* Secondmax = max;
Max = buffer [I];
}
Else if (buffer [I]> * secondmax & buffer [I] <max)
* Secondmax = buffer [I];
}
If (* secondmax = minnumber) // The numbers are all the same.
Return find_fail;
Return find_sucess;
}
The second largest number of queries is actually accompanied by the maximum number of queries.
1, If the current element is greater than the max, the second largest is equal to the original max, and then the value of the current element is assigned to Max.
2, If the value of the current element is greater than the value of the second secondmax and smaller than the value of the maximum Max, the value of the current element is assigned to secondmax. ――The judgment condition cannot only be greater than the second largest number of secondmax, otherwise we cannot process it."99,99, 88,86, 68,66"This situation.
PS: when calling this function, you need to determine whether the return value of the function isFind_sucessCan be used.