程序找到数组的第二大元素(Program to find the second largest element of an array)

优质
小牛编辑
135浏览
2023-12-01

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

算法 (Algorithm)

让我们首先看看该程序的逐步程序应该是什么 -

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

伪代码 (Pseudocode)

现在让我们看看这个算法的伪代码 -

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

实现 (Implementation)

这个伪代码现在可以在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