Java 程序用于查找数组中的最大值、最小值、第二大元素和第二小元素


为了在数组中查找最大值、最小值、第二大元素和第二小元素,代码如下 -

示例

 实时演示

import java.util.*;
public class Demo {
   public static void main(String []args){
      int arr[] = {55, 10, 8, 90, 43, 87, 95, 25, 50, 12};
      System.out.println("Array = "+Arrays.toString(arr));
      Arrays.sort(arr);
      System.out.println("Sorted Array = "+Arrays.toString(arr));
      System.out.println("Smallest element = "+arr[0]);
      System.out.println("2nd Smallest element = "+arr[0]);
      System.out.println("Largest element = "+arr[9]);
      System.out.println("2nd Largest element = "+arr[8]);
   }
}

输出

Array = [55, 10, 8, 90, 43, 87, 95, 25, 50, 12]
Sorted Array = [8, 10, 12, 25, 43, 50, 55, 87, 90, 95]
Smallest element = 8
2nd Smallest element = 8
Largest element = 95
2nd Largest element = 90

示例

现在让我们看另一个示例

 实时演示

import java.util.*;
public class Demo {
   public static void main(String []args){
      int a;
      int arr[] = {55, 10, 8, 90, 43, 87, 95, 25, 50, 12};
      System.out.println("Array = "+Arrays.toString(arr));
      int count = arr.length;
      for (int i = 0; i < count; i++) {
         for (int j = i + 1; j < count; j++) {
            if (arr[i] > arr[j]) {
               a = arr[i];
               arr[i] = arr[j];
               arr[j] = a;
            }
         }
      }
      System.out.println("Smallest: "+arr[0]);
      System.out.println("Largest: "+arr[count-1]);
      System.out.println("Second Smallest: "+arr[1]);
      System.out.println("Second Largest: "+arr[count-2]);
   }
}

输出

Array = [55, 10, 8, 90, 43, 87, 95, 25, 50, 12]
Smallest: 8
Largest: 95
Second Smallest: 10
Second Largest: 90

更新于:2020年1月2日

3K+ 浏览量

职业一触即发

完成课程,获得认证

开始学习
广告