Finding the second smallest integer in array

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

    Try this one.

        public static void main(String args[]){
            int[] array = new int[]{10, 30, 15, 8, 20, 4};
    
            int min, secondMin;
    
            if (array[0] > array[1]){
                min = array[1];
                secondMin = array[0];
            }
            else{
                min = array[0];
                secondMin = array[1];
            }
    
            for (int i=2; i min) && (array[i] < secondMin)){
                    secondMin = array[i];
                }
            }
           System.out.println(secondMin);
      }
    

提交回复
热议问题