Finding the second smallest integer in array

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

    public class SecondSmallestNumberInArray 
            {
                public static void main(String[] args) 
                {
                    int arr[] = { 99, 76, 47, 85, 929, 52, 48, 36, 66, 81, 9 };
                    int smallest = arr[0];
                    int secondSmallest = arr[0];
    
                    System.out.println("The given array is:");
                    boolean find = false;
                    boolean flag = true;
    
                    for (int i = 0; i < arr.length; i++) 
                    {
                        System.out.print(arr[i] + "  ");
                    }
    
                    System.out.println("");
    
                    while (flag) 
                    {
                        for (int i = 0; i < arr.length; i++) 
                        {
                            if (arr[i] < smallest) 
                            {   
                                find = true;
                                secondSmallest = smallest;
                                smallest = arr[i];
                            } else if (arr[i] < secondSmallest) {   
                                find = true;
                                secondSmallest = arr[i];
                            }
                        }
                        if (find) {
                            System.out.println("\nSecond Smallest number is Array : ->  " + secondSmallest);
                            flag = false;
                        } else {
                            smallest = arr[1];
                            secondSmallest = arr[1];
                        }
                    }
                }
            }
    
        **Output is**
    
        D:\Java>java SecondSmallestNumberInArray
    
        The given array is:
    
        99  76  47  85  929  52  48  36  66  81  9
    
        Second Smallest number is Array : ->  36
    
        D:\Java>
    

提交回复
热议问题