算法寻找数组中的第二大数

方法一:

[cpp]  view plain copy
  1. #include "stdio.h"  
  2. #include "stdlib.h"  
  3.   
  4. //初始化最大值为a[0],次大值为a[1],遍历一次,每次比较并更新最大值和次大值,最后就可以得到次大值。  
  5. int findsecondmaxvalue(int *a,int size)  
  6. {  
  7.     int i,max,s_max;  
  8.     max=a[0];  //最大值  
  9.     s_max=a[1];  //次大值  
  10.     for(i=0;i
  11.     {  
  12.         if(a[i]>max)  
  13.         {  
  14.             s_max=max;  //更新最大值和次大值  
  15.             max=a[i];  
  16.         }  
  17.         else if(a[i]s_max)   //更新次大值  
  18.             s_max=a[i];  
  19.     }  
  20.     return s_max;  
  21. }  
  22.   
  23. int main(void)  
  24. {  
  25.     int second,a[]={111,23,3,5,652,2,3};  
  26.     second=findsecondmaxvalue(a,sizeof(a)/sizeof(a[0]));  
  27.     printf("这个数组中的次大值为:%d\n",second);  
  28.     system("pause");  
  29.     return 0;  
  30. }  


 方法二: 

[cpp]  view plain copy
  1. /*  
  2. 写一个函数找出一个整数数组中,第二大的数(microsoft)  
  3. 要求效率尽可能高  
  4. */   
  5. #include "stdio.h"    
  6. #include "stdlib.h"    
  7.   
  8. int find(int *a,int n)   //从数组的第二个元素开始查找  
  9. {    
  10.     int i,second=a[1];  
  11.     for(i=1;i
  12.     {  
  13.         if(a[i]>second)  
  14.             second=a[i];  
  15.     }  
  16.     return second;  
  17. }  
  18.   
  19. int findsecondmaxvalue(int *a,int size)    
  20. {    
  21.     int i,first,second;  
  22.     first=second=a[0];  
  23.     for(i=1;i
  24.     {  
  25.         if(a[i]>first)  
  26.         {  
  27.             second=first;  
  28.             first=a[i];  
  29.         }  
  30.         else if(a[i]second)  
  31.             second=a[i];  
  32.     }  
  33.     //最大值和次大值相等(数组的第一个元素为最大值的时候)    
  34.     if(first==second)  
  35.     {  
  36.         second=find(a,size); //从数组的第二个元素开始找一个最大值的即为次大值  
  37.     }  
  38.     return second;  
  39. }  
  40.   
  41. int main(void)  
  42. {  
  43.     int a[] = {12012, 3, 45, 5, 66, 232, 65, 7, 8, 898, 56, 878, 170, 13, 5};  
  44.     int second=findsecondmaxvalue(a,sizeof(a)/sizeof(a[0]));  
  45.     printf("这个数组中的次大值为:%d\n",second);  
  46.     system("pause");  
  47.     return 0;  
  48. }  

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29012686/viewspace-1149848/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29012686/viewspace-1149848/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值