Java输出数组次大值对应的下标

    技术2023-05-31  77

    package practice; import java.util.Scanner; public class IndexOf2ndLargestValue { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int arr[] = new int[10]; for (int i = 0; i < arr.length; i++) { System.out.print("请输入第" + (i + 1) + "个数组元素:"); arr[i] = sc.nextInt(); } int max = arr[0]; // 假设数组接收的第一个值为最大值 int maxIndex = 0; // 最大值索引 int greatValue = 0; // 次大值 int greatValueIndex = 0; // 次大值索引 for (int i = 1; i < arr.length; i++) { if (max < arr[i]) { // 假定的最大值小于数组的后一个元素时 greatValue = max; // 此时原最大值并非最大值,转而说明它是次大值 greatValueIndex = maxIndex; // 最大值索引降级为次大值索引 max = arr[i]; // 最大值变量接收后一个新的最大值 maxIndex = i; // 最大值索引升级为当前循环变量的值 } else { // 假定的最大值一开始就大于数组的后一个元素 if (greatValue < arr[i]) { // 判断次大值是否小于数组的后一个元素 greatValue = arr[i]; // 使用新的次大值覆盖原有的次大值 greatValueIndex = i; // 次大值的下标跟随循环变量的改变而改变 } } } System.out.println("\n提示:数组元素的次大值为:" + greatValue + ",其对应的索引下标为:" + greatValueIndex); sc.close(); } }
    Processed: 0.020, SQL: 9