c语言经典算法——查找一个整数数组中第二大数
生活随笔
收集整理的這篇文章主要介紹了
c语言经典算法——查找一个整数数组中第二大数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
https://www.cnblogs.com/dootoo/p/4473958.html
題目:?實現(xiàn)一個函數(shù),查找一個整數(shù)數(shù)組中第二大數(shù)。
算法思想:
設置兩個變量max1和max2,用來保存最大數(shù)和第二大數(shù),然后將數(shù)組剩余的數(shù)依次與這兩個數(shù)比較,如果這個數(shù)a比max1大,則先將max1賦給max2,使原先最大的數(shù)成為第二大的數(shù),再將這個數(shù)a賦給max1,如果這個數(shù)a比max1小但比max2大,則將這個數(shù)a賦值給max2,依次類推,直到數(shù)組中的數(shù)都比較完。
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("原數(shù)組如下:\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 else 44 { 45 if (i == 1) 46 max2 = array[i]; 47 else if (array[i]>max2) 48 max2 = array[i]; 49 } 50 } 51 return max2; 52 }總結(jié)
以上是生活随笔為你收集整理的c语言经典算法——查找一个整数数组中第二大数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: lol卡兹克和剑圣哪个好
- 下一篇: 两个栈实现一个队列/两个队列实现一个栈