javaarrayssorting

Method to find second highest number in an array in java


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);
    }
}

Solution

  • 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.