Finding the second smallest integer in array

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

    Here is TimeComlexity Linear O(N):

      public static int secondSmallest(int[] arr) {
        if(arr==null || arr.length < 2) {
            throw new IllegalArgumentException("Input array too small");
        }
    
        //implement
        int firstSmall = -1;
        int secondSmall = -1;
    
        //traverse to find 1st small integer on array
        for (int i = 0; iarr[i])
                firstSmall = i;
    
         //traverse to array find 2 integer, and skip first small
        for (int i = 0;i arr[i]))
                secondSmall = i;
        }
    
        return arr[secondSmall];
    }
    

提交回复
热议问题