尋找數組中的第二大數

來源:互聯網
上載者:User

方法一:

#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;i<size;i++)    {        if(a[i]>max)        {s_max=max;  //更新最大值和次大值max=a[i];        }else if(a[i]<max && 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;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];}//最大值和次大值相等(數組的第一個元素為最大值的時候)  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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.