c語言經典演算法——尋找一個整數數組中第二大數

來源:互聯網
上載者:User

標籤:

題目: 實現一個函數,尋找一個整數數組中第二大數。

演算法思想:

設定兩個變數max1和max2,用來儲存最大數和第二大數,然後將數組剩餘的數依次與這兩個數比較,如果這個數a比max1大,則先將max1賦給max2,使原先最大的數成為第二大的數,再將這個數a賦給max1,如果這個數a比max1小但比max2大,則將這個數a賦值給max2,依次類推,直到數組中的數都比較完。

c語言代碼:

 1 #include<stdio.h> 2 #include<stdlib.h> 3 #define N 10 4 void produce_random_array(int array[], int n); 5 void show_array(int array[], int n); 6 int search_second_max(int array[], int n); 7 int main(int agrc, char *agrv[]) 8 { 9     int array[N];10     produce_random_array(array, N);11     printf("原數組如下:\n");12     show_array(array, N);13     printf("\nthe second_max is: %d\n", search_second_max(array, N));14     system("pause");15     return 0;16 }17 void produce_random_array(int array[], int n)18 {19     int i;20     srand(time(NULL));21     for (i = 0; i < n; i++)22     {23         array[i] = rand() % 100;24     }25 }26 void show_array(int array[], int n)27 {28     int i;29     for (i = 0; i < n; i++)30         printf("%-3d", array[i]);31 }32 int search_second_max(int array[], int n)33 {34     int max1, max2, i;35     max1 = array[0];36     for (i = 1; i < n; i++)37     {38         if (array[i]>max1)39         {40             max2 = max1;41             max1 = array[i];            42         }43         else44         {45             if (i == 1)46                 max2 = array[i];47             else if (array[i]>max2)48                 max2 = array[i];49         }50     }51     return max2;52 }

 

c語言經典演算法——尋找一個整數數組中第二大數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.