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