Java - Array.sort用法

import java.util.Arrays;
import java.util.Comparator;
 
public class SortUsage {
	/**
	 * omparator完成如下排序:
	 * 
	 * 1. 一维数组降序排列;
	 * 
	 * 2. 二维数组按照某列排序
	 */
	
	public static void MatrixSortByCol(int[][] matrix) {
	    if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
		    return;
	    Arrays.sort(matrix, new Comparator() {
            @Override
            public int compare(int[] x, int[] y) {
                if(x[0] < y[0])
                    return 1;
                else if(x[0] > y[0])
                    return -1;
                else
                    return 0;
            }
        });
         
        //打印
        for(int[] item : matrix){
            System.out.println(Arrays.toString(item));
        }
	}
	
	public static void descendingSort(int[] nums) {
		if (nums == null || nums.length == 0)
			return;
		System.out.print("数组按照升序排列: ");
		Arrays.sort(nums);
		System.out.println(Arrays.toString(nums));
		
		Integer[] number = new Integer[nums.length];
		for (int i = 0; i < nums.length; i++)
			number[i] = nums[i];
		
		Arrays.sort(number, new Comparator() {
			@Override
			public int compare(Integer x1, Integer x2) {
				if (x1 - x2 > 0)
					return -1;
				else if (x1 - x2 < 0)
					return 1;
				else
					return 0;
			}
		} );
		System.out.println("数组按照降序排列: " + Arrays.toString(nums));
	}
	
    public static void main(String[] args) {        
    	int[][] matrix = {{2, 3, 1, 4}, {7, 3, 9, 1}, {9, 8, 10, 3}};
    	MatrixSortByCol(matrix);
    	
    	int[] nums = {2, 1, 4, 6, 3, 9, 7};
    	descendingSort(nums);
    }
}

你可能感兴趣的:(Java)