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; } } }