Java 数组第二大的值

来源:互联网 发布:ubuntu ntfs 编辑:程序博客网 时间:2024/06/07 21:05

           

             package fish;


          public class Job2 {
/**
     * 找出数组中数第二大的值
     * @param arraym 
     * @author shaobn
     */
public static void main(String[] args) {
    
   int[] arr = { 5, 41, 65, 55, 32, 45, 13, 18, 55, 4, 21, 21, 54, 2, 4, 87, 74, 54 };
    
   int first = Integer.MIN_VALUE, second = first;  //int基本类型,Integer是他的包装类,这是一个类。
    
   for(int i = 0, len = arr.length; i < len; i++) {
        
       if(arr[i] > second) {
            
           if(arr[i] > first) {
                
               second = first;
                
               first = arr[i];
                
           } else {
                
               second = arr[i];
                
           }
            
       }
        
   }
     



package fish;


public class Job2 {
/**
     * 找出数组中数第二大的值
     * @param arraym
     * @author shaobn
     */
public static void main(String[] args){
int[] arr = { 5, 41, 65, 55, 32, 45, 13, 18, 55, 4, 21, 21, 54, 2, 4, 87, 74, 54 };
   int first = Integer.MIN_VALUE, second = first;
   int min= Integer.MIN_VALUE;
   for(int i = 0, len = arr.length; i < len; i++) { 
       if(arr[i] > second) { 
           if(arr[i] > first) { 
               second = first;                
               first = arr[i];                
           } else if(arr[i]<first){                 
               second = arr[i];  
           }else{
            min=first=arr[i];
           }  
       } 
   }
   if(first==min){
    System.out.print("數組中數字相等");
   }else{
    System.out.println(second);
   }


}
}                   




                package fish;

                public static void getMethod_5(int[] array){
       int temp = 0;
       int len = array.length;
       for(int i=0;i<len;i++){
           if(i==len-1){
               break;
           }
           for(int j = i+1;j<len;j++){
               if(array[i]>=array[j]){
                   continue;
               }else {
                   temp = array[j];
                   array[j] = array[i];
                   array[i] = temp;
                    
               }
                
           }
            
       }
       System.out.println(array[1]);
        
        
        
   }




0 0
原创粉丝点击