第一種方法
#include "stdio.h"??
#include "stdlib.h"? ??
//初始化最大值為a[0],次大值為a[1],遍歷一次,每次比較并更新最大值和次大值,最后就可以得到次大值。?
?int findsecondmaxvalue(int *a,int size)?
?{ ? ? ?
? ? ? ? int i,max,s_max;? ? ?
? ? ? ? max=a[0];? //最大值? ? ?
? ? ? ? s_max=a[1];? //次大值? ? ??
? ? ? ? for(i=0;imax)? ? ? ? ? {? ? ? ? ? ? ??
? ? ? ? ? ? ? s_max=max;? //更新最大值和次大值? ? ? ? ? ? ??
? ? ? ? ? ? ? max=a[i];? ? ? ? ??
? ? ? ? ? } ?else if(a[i]s_max) ?{//更新次大值
? ? ? ? ? ? ? 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("這個數組中的次大值為:%d\n",second);
? ? ? ?system("pause");
? ? ? ?return 0;
}
第二種方法
/*? 寫一個函數找出一個整數數組中,第二大的數(microsoft)? 要求效率盡可能高? */? #include "stdio.h"? ?
?#include "stdlib.h"? ? ?
int find(int *a,int n)? //從數組的第二個元素開始查找??
{? ? ? ?
? ? ? ? int i,second=a[1];? ? ?
? ? ? ? for(i=1;isecond){? ? ? ? ? ? ?
? ? ? ? second=a[i]; ? ? ?
? ? ? ? }? ? ??
? ? ? ? return second;?
?}? ??
int findsecondmaxvalue(int *a,int size)? ??
{? ? ? ?
? ? ? int i,first,second;? ? ??
? ? ? first=second=a[0];? ? ??
? ? ? for(i=1;ifirst){? ? ? ? ? ? ??
? ? ? ? ? ?second=first;? ? ? ? ? ? ??
? ? ? ? ? ?first=a[i];? ? ? ? ??
? ? ? } else if(a[i]second){
? ? ? ? ? ?second=a[i];
? ? ? }
? ? ? ?//最大值和次大值相等(數組的第一個元素為最大值的時候)
? ? ? ?if(first==second){
? ? ? ? ? ? ? ?second=find(a,size); //從數組的第二個元素開始找一個最大值的即為次大值
? ? ? ?}
? ? ? ? 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("這個數組中的次大值為:%d\n",second);
? ? ? ? system("pause");
? ? ? ? return 0;
}