Home > Mobile >  Method to find second highest number in an array in java
Method to find second highest number in an array in java

Time:06-16

Getting output of 0 each time when im ment to get 3 looked over my code my not sure where i have gone wrong i can do it without using a method i know but just trying to practice java




public class App {
    
public static int second(int a[],int n) {
    int[] arr = new int [n];
    int temp;
    for(int i=0;i<n;i  ) {
        for(int j=i 1;j<n;j  ) {
            if(arr[i] > arr[j]) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr[n-2];
}



public static void main(String[] args) {


int[] arr = {1,3,2,5,3};
int n = 5;
int result = second(arr,n);
System.out.println(result);
    
}

}


CodePudding user response:

You could change the array parameter name arr and remove the declaration or copy the values from a to arr.

public static int second(int arr[],int n) {
    int temp;
    for(int i=0;i<n;i  ) {
        for(int j=i 1;j<n;j  ) {
            if(arr[i] > arr[j]) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr[n-2];
}

The reason you get zero is because the primitive int cannot be null. So, when you create the array of length 5, it starts out filled with zeroes.

CodePudding user response:

Doing it by using streams:

public static int second(int a[]) {
    return Arrays.stream(a)
            .sorted()
            .skip(a.length - 2)
            .findFirst()
            .getAsInt();
}

I removed the second argument. It sorts your array and skips all the elements prior to the one you want, before picking the now first element.

  • Related