简体   繁体   中英

finding two max values in Java

Can anyone help me please? I want to find the maximum and the 2nd maximum value of an Array using a method. I already know how I can get the Minimum and the 2nd minimum value, it's basically almost the same, but the output is still wrong ? This is the method how I find the two minimum values.

public static void minimum( int [] a ) {
int min;
for (int i = 0; i< a.length; i++)  {
    for (int j = min = i; j< a.length; j++) {
        if (a[j] < a[min]) min = j;
        if(min>i) {
            int temp = a [i];
            a [i] = a [min];
            a [min] = temp;

        } 
}

so , to find the maximum I thought it's just to change < to > from this line : if (a[j] < a[min]) min = j;` so, instead of swapping smaller values, bigger values will be swapped. But it's wrong and I don't get it.

Thank you !

If you want to code by yourself,the code may help you:

public static void maxNum(int[] a) {
    int length = a.length;
    if (length == 0) {
        System.out.println("the length of input array 0");
        return;
    }
    if (length == 1) {
        System.out.println("the max is " + a[0]);
        return;
    }
    int max = a[0] > a[1] ? a[0] : a[1];
    int secondMax = a[0] > a[1] ? a[1] : a[0];
    for (int i = 2; i < length; i++) {
        int value = a[i];
        if (value > max) {
            int tmp = max;
            max = value;
            secondMax = tmp;
        } else if (value > secondMax) {
            secondMax = value;
        }
    }
    System.out.println("the max is " + max);
    System.out.println("the second max is " + secondMax);
}

If you don't want to code yourself,you can use tools in java like Arrays.sort() to sort the array first and get what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM