Algorithms

Get the second smallest element in array

seoca 2019. 9. 7. 11:11

 

 

Example Code

 
public class Main{
    public static void main(String args[]) {
        int arr[] = {2,4,1,7,0};
        System.out.println(min(arr));
    }
    public static int min(int[] arr){
        int min = arr[0]; 
        int sec = arr[1];
        for(int i = 0; i < arr.length; i++){
            if(arr[i] < min){ //get the smallest
                sec = min; //should change sec here
                min = arr[i];
            }else if(arr[i] < sec){//get the second smallest 
                sec = arr[i];
            }
        }
        return sec;
    }
}