Java-求一个数组的最大值和次大值

1.求一个数组的最大值和次大值

        在一个方法中实现从一个数组中找到该数组的最大值和次大值并返回。

示例运行如下:

import java.util.Scanner;
public class FMaxSec {
   private static int max;
   private static int sec;
/**在一个方法中实现从一个数组中找到该数组的最大值和次大值并返回。*/
    public static void main(String[] args) {
        int[] arr;
        int n;
        Scanner scanner = new Scanner(System.in);
        System.out.print("please input the length of the array:");
        n = scanner .nextInt();
        arr = new int[n];
        for (int i = 0; i < n; i++) {
            System.out.print("array[" + (i + 1) + "]=");
            arr[i] = scanner.nextInt();
        }
        findMaxSec(arr);
    }
private static void findMaxSec(int[] arr) {
    if (arr.length>=2) {
        max = arr[0];
        for (int i=0;i<arr.length-1;i++) {
            if (arr[i]>arr[i+1]) {
                int temp = arr[i];
                arr[i]=arr[i+1];
                arr[i+1]=temp;
           }
        }
        max = arr[arr.length-1];   
        sec = arr[0];
        for (int i=0;i<arr.length-2;i++) {
            if (arr[i]>arr[i+1]) {
                int temp = arr[i];
                arr[i]=arr[i+1];
                arr[i+1]=temp;
            }
        }
        sec = arr[arr.length-2];
        System.out.println("最大值"+max);
        System.out.println("次大值"+sec);
    } else {
        System.out.println("最大值"+arr[0]);
    }
}
}

 

用例1:

输入

5 45 76 45 86 -98 最大值86 次大值76

输出

please input the length of the array:array[1]=array[2]=array[3]=array[4]=array[5]=最大值86 次大值76

用例2:

输入

3 4 4 4

输出

please input the length of the array:array[1]=array[2]=array[3]=最大值4 次大值4

用例3:

输入

2 456 3423

输出

please input the length of the array:array[1]=array[2]=最大值3423 次大值456

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值