Array.sort()排序问题

Array.sort()用法

一维

升序

首先对于sort()函数来说默认是升序的

import java.util.Arrays;
 
public class helloworld {
    public static void main(String[] args) {
        int[] arr={1,4,3,6,7,9};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

//输出
//1 3 4 6 7 9

区间选择排序

区间排序sort(T[] a,int formIndex, int toIndex)

参数说明

formIndex:起始序号,从0开始

toIndex:结束序号,在该序号的前一位结束

例如: 1 2 3 4 5 6 7

排序formIndex:0 toIndex:7

图片

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
 
public class helloworld {
    public static void main(String[] args) {
        Integer[] arr2={1,4,3,8,2,9,11,3};
        Arrays.sort(arr2,2,5);
        System.out.println(Arrays.toString(arr2));
    }
}

//输出1 4 2 3 8 9 11 3

降序

如果想要降序,Arrays.sort(scores,Collections.reverseOrder())

不能用int这个类型了,要用Integer,不能使用基本类型(int,double, char),如果是int型需要改成Integer,float要改成Float

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
 
public class helloworld {
    public static void main(String[] args) {
        Integer[] arr2={1,4,3,6,7,9,11};
        Arrays.sort(arr2, Collections.reverseOrder());
        System.out.println(Arrays.toString(arr2));
    }
}

//输出  11 9 7 6 4 3 1

二维

在 Java 中,Arrays.sort() 是一个常用的静态方法,用于对数组进行排序。虽然 Arrays.sort() 仅支持对一维数组进行排序,但我们可以通过自定义 Comparator 比较器来实现对二维数组的排序。

使用自定义Comparator

import java.util.Arrays;
import java.util.Comparator;

public class Main {
	public static void main(String[] args) {
		int[][] points = {{10, 16}, {2, 8}, {1, 6}, {6, 12}};
		// 对二维数组按照每行数组的第一个元素进行排序
		Arrays.sort(points, new Comparator<int[]>() {
		@Override
		public int compare(int[] o1, int[] o2) {
		// 按照从小到大排序
			return o1[0] - o2[0];
		}
		});
		for (int[] point : points) {
			for (int i : point) {
				System.out.print(i + " ");
			}
			System.out.println();
		}
	}
}

使用lambda表达式

import java.util.Arrays;

public class Main {
	public static void main(String[] args) {
		int[][] points = {{10, 16}, {2, 8}, {1, 6}, {6, 12}};
		// 对二维数组按照每行数组的第一个元素进行排序
		Arrays.sort(points, (o1, o2) -> o1[0] - o2[0]);
		for (int[] point : points) {
			for (int i : point) {
				System.out.print(i + " ");
			}
			System.out.println();
		}
	}
}

使用Comparator.comparingInt()方法

import java.util.Arrays;
import java.util.Comparator;

public class Main {
	public static void main(String[] args) {
		int[][] points = {{10, 16}, {2, 8}, {1, 6}, {6, 12}};
		// 对二维数组按照每行数组的第一个元素进行排序
		Arrays.sort(points, Comparator.comparingInt(o -> o[0]));
		for (int[] point : points) {
			for (int i : point) {
				System.out.print(i + " ");
			}
			System.out.println();
		}
	}
}
posted @ 2025-03-01 15:26  狐狸胡兔  阅读(242)  评论(0)    收藏  举报