Finding the second smallest integer in array

后端 未结 19 1942
無奈伤痛
無奈伤痛 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:22

    public static int getSecondSmallest(int[] arr){
            int smallest = Integer.MAX_VALUE;
            int secondSmallest = Integer.MAX_VALUE;
            for(int i=0;i arr[i]){
                    secondSmallest = smallest;
                    smallest = arr[i];
                }else if (secondSmallest > arr[i] && arr[i] != smallest){
                secondSmallest = arr[i];
            }
                System.out.println(i+" "+smallest+" "+secondSmallest);
            }
            return secondSmallest;
        }
    

    Just gave it a try with some of the test cases and it worked. Please check if it is correct!

提交回复
热议问题