C Language Classic algorithm--find the second largest number in an array of integers

Source: Internet
Author: User

Title: Implement a function to find the second largest number in an array of integers.

Algorithm idea:

Set two variables max1 and MAX2 to hold the largest and second largest numbers, and then compare the remaining number of the array to these two numbers sequentially, if the number a is larger than Max1, first assign max1 to Max2 so that the largest number is the second biggest number, and then assign the number A to Max1, If the number a is smaller than max1 but larger than MAX2, assign this number A to max2, and so on, until the number in the array is compared.

C Language code:

1#include <stdio.h>2#include <stdlib.h>3 #defineN 104 voidProduce_random_array (intArray[],intn);5 voidShow_array (intArray[],intn);6 intSearch_second_max (intArray[],intn);7 intMainintAGRC,Char*agrv[])8 {9     intArray[n];Ten Produce_random_array (array, N); Oneprintf"The original array is as follows: \ n"); A Show_array (array, N); -printf"\nthe Second_max is:%d\n", Search_second_max (array, N)); -System"Pause"); the     return 0; - } - voidProduce_random_array (intArray[],intN) - { +     inti; - Srand (Time (NULL)); +      for(i =0; I < n; i++) A     { atArray[i] = rand ()% -; -     } - } - voidShow_array (intArray[],intN) - { -     inti; in      for(i =0; I < n; i++) -printf"%-3d", Array[i]); to } + intSearch_second_max (intArray[],intN) - { the     intmax1, Max2, I; *MAX1 = array[0]; $      for(i =1; I < n; i++)Panax Notoginseng     { -         if(array[i]>max1) the         { +MAX2 =max1; AMax1 =Array[i];  the         } +         Else -         { $             if(i = =1) $MAX2 =Array[i]; -             Else if(array[i]>max2) -MAX2 =Array[i]; the         } -     }Wuyi     returnMax2; the}

C Language Classic algorithm--find the second largest number in an array of integers

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.