查找 C 数组中的第二大元素



查找数组中的第二大值是经典的 C 语言数组程序。该程序使你深入了解迭代、数组和条件运算符。我们迭代地检查每个元素,以确定最大和第二大元素。

算法

首先,我们来看看该程序的分步过程 -

START
   Step 1 → Take an array A and define its values
   Step 2 → Declare largest and second as integer
   Step 3 → Assign first two values of array A to largest and second
   Step 4 → Assign the large value to largest and second largest to second
   Step 5 → Iterate for Array A
   Step 6 → If A[n] > largest, Assign largest.value to second and Assign A[n] to largest
   Step 7 → Else If A[n] > second, Assign A[n] to second
   Step 8 → Loop Terminates
   Step 9 → Display largest and second
STOP

伪代码

现在,我们来看看该算法的伪代码 -

procedure largest_array(A)

   Declare largest and second as integer

   IF A[0] is greater than A[1] THEN 
      largest ← A[0]
      second ← A[1]
   ELSE
      largest ← A[1]
      second ← A[0]
   ENDIF

   FOR EACH value in A DO
      IF A[n] is greater than largest THEN
         second ← largest
         largest ← A[n]
      ELSE IF second is less than A[n] THEN
         second ← A[n]
      END IF

   END FOR
   Display largest and second

end procedure

实现

现在,可以在 C 语言程序中实现该伪代码,如下所示 -

#include <stdio.h>

int main() {
   int array[10] = {101, 11, 3, 4, 50, 69, 7, 8, 9, 0};
   int loop, largest, second;

   if(array[0] > array[1]) {
      largest = array[0];
      second  = array[1];
   } else {
      largest = array[1];
      second  = array[0];
   }

   for(loop = 2; loop < 10; loop++) {
      if( largest < array[loop] ) {
         second = largest;
         largest = array[loop];
      } else if( second < array[loop] ) {
         second =  array[loop];
      }
   }

   printf("Largest - %d \nSecond - %d \n", largest, second);   

   return 0;
}

输出应该如下所示 -

Largest - 101
Second - 69
array_examples_in_c.htm
广告