How do I find the second largest number in an array

  • 2020-04-01 23:42:12
  • OfStack

Method one:

#include "stdio.h"
#include "stdlib.h"
//Initialize the maximum value as a[0], and the sub-large value as a[1], traverse once, compare and update the maximum value and sub-large value each time, and finally get the sub-large value.
int findsecondmaxvalue(int *a,int size)
{
    int i,max,s_max;
    max=a[0];  //The maximum
 s_max=a[1];  //Great value
    for(i=0;i<size;i++)
    {
        if(a[i]>max)
        {
   s_max=max;  // update The maximum and Great value
   max=a[i];
        }
  else if(a[i]<max && a[i]>s_max)   // update Great value
   s_max=a[i];
    }
 return s_max;
}
int main(void)
{
    int second,a[]={111,23,3,5,652,2,3};
    second=findsecondmaxvalue(a,sizeof(a)/sizeof(a[0]));
    printf(" In this array Great value To: %dn",second);
 system("pause");
 return 0;
}

Method 2:

 
#include "stdio.h"  
#include "stdlib.h"  
int find(int *a,int n)   //Start with the second element of the array
{  
 int i,second=a[1];
 for(i=1;i<n;i++)
 {
  if(a[i]>second)
   second=a[i];
 }
 return second;
}
int findsecondmaxvalue(int *a,int size)  
{  
 int i,first,second;
 first=second=a[0];
 for(i=1;i<size;i++)
 {
  if(a[i]>first)
  {
   second=first;
   first=a[i];
  }
  else if(a[i]<first && a[i]>second)
   second=a[i];
 }
 //The maximum value is the same as the second largest value (when the first element of the array is the maximum)& PI;
 if(first==second)
 {
  second=find(a,size); //Starting with the second element of the array to find a maximum value is the next largest value
 }
 return second;
}
int main(void)
{
 int a[] = {12012, 3, 45, 5, 66, 232, 65, 7, 8, 898, 56, 878, 170, 13, 5};
 int second=findsecondmaxvalue(a,sizeof(a)/sizeof(a[0]));
 printf(" The next largest value in this array is: %dn",second);
 system("pause");
 return 0;
}


Related articles: