找出数组中第二大的值

如何找出数组中的第二大数

算法思路:

方法1:

  快速排序后根据数组下标获得数组中第二大的值

方法2:

(1)首先定义一个变量来存储数组的最大数,初始值为数组首元素;另一个变量用来存储数组元素的第二大数,初始值为最小负数 -32767,然后遍历数组元素。

(2)如果数组元素的值比最大数变量的值大,则将第二大变量的值更新为最大数变量的值,最大数变量的值更新为该元素的值;如果数组元素的值比最大数的值小,则判断该数组元素的值是否比第二大数的值大,如果大,则更新第二大数的值为该数组元素的值。

代码实现:

package Array;

/**
 * 获取数组中第二大的数
 */
public class SecondMax {
    public static int FindSecMax(int data[]){
        int count = data.length;
        int maxnumber = data[0];
        int sec_max = Integer.MIN_VALUE;//最小负整数
        for (int i=1;i<count;i++){//循环遍历一遍
            if (data[i]>maxnumber){//当前数组元素的值是比最大的数大
                sec_max=maxnumber;//更新第二大的数值为先前的最大值
                maxnumber = data[i];//更新先前的最大值为当前数组元素的值
            }
            else{
                if (data[i]>sec_max){//当前数组元素的值是比最大值小则与第二大值比较
                    sec_max = data[i];//如果当前数组元素的值比第二大值大,则更新第二大值
                }
            }
        }
        return sec_max;
    }
    public static void main(String[] args){
        int[] array = {7,3,19,40,4,7,1};
        System.out.println(FindSecMax(array));
    }
}

猜你喜欢

转载自blog.csdn.net/hd12370/article/details/81056569