Finding the second smallest integer in array

后端 未结 19 1911
無奈伤痛
無奈伤痛 2021-01-18 05:48

We are required in our assignment to find the second smallest integer in one array recursively. However, for the sake of understanding the subject more, I want to do it iter

19条回答
  •  醉话见心
    2021-01-18 06:20

    public static int findSecondSmallest(int[] elements) {
        if (elements == null || elements.length < 2) {
            throw new IllegalArgumentException();
        } 
        int smallest = elements[0]; 
        int secondSmallest = elements[0]; 
        for (int i = 1; i < elements.length; i++) {
            if (elements[i] < smallest) {
                secondSmallest = smallest;
                smallest = elements[i];
            } 
            else if (elements[i] < secondSmallest) {
                secondSmallest = elements[i];
            }
        }
        return secondSmallest;
    }
    

提交回复
热议问题