Java中數組比較大小


1、Arrays.sort(數組名)

對數組中的所有元素進行排序,並且是按照從小到大的順序進行的。

Integer[] test = new Integer[n];
Arrays.sort(test);

 

2、Arrays.sort(數組名,起始下標,終止下標)

對數組中的部分元素進行排序,即從起始下標到終止下標-1的元素排序。

 

3、使用比較器比較的方法

public class t6 {
    static int n;
    public static void main(String[] args) {    
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入個數:");
        int n = sc.nextInt();
        
        Integer[] test = new Integer[n];
        for(int i = 0; i < n; i++) {
            test[i] = sc.nextInt();
        }
        
        MyComparator cmp = new MyComparator();
        Arrays.sort(test, cmp);
        
        for(Integer p: test) {
            System.out.println(p);
        }
    }
}




class MyComparator implements Comparator<Integer>{
    @Override
    public int compare(Integer o1, Integer o2) {
        return o1 - o2; //從小到大        
    }
}
class MyComparator implements Comparator<Integer>{
    @Override
    public int compare(Integer o1, Integer o2) {
        if(o1 > o2) {
            return 1; 
        }else if (o1 < o2) {
            return -1;
        }else {
            return 0;            
        }
    }
}
class MyComparator implements Comparator<Integer>{
	@Override
	public int compare(Integer o1, Integer o2) {
		return o2 - o1;  //從大到小
	}
}
class MyComparator implements Comparator<Integer>{
    @Override
    public int compare(Integer o1, Integer o2) {
        if(o1 < o2) {
            return 1; 
        }else if (o1 > o2) {
            return -1;
        }else {
            return 0;            
        }
    }
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM