JAVA.Arrays.sort(排序)

Arrays.sort

从小到大排序

常用方法:
Arrays.sort(数组名,起始下表,终止下表)
Arrays.sort(数组名)
举例:

点击查看代码
/**
*输入案例:
*5 4 3 2 1
*输出:
*4.0 5.0 3.0 2.0 1.0
*1.0 2.0 3.0 4.0 5.0
**/
import java.util.*;
import java.util.Arrays;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		double[] a=new double[5];
		for(int i=0;i<5;i++) {
			a[i]=sc.nextDouble();
		}
		Arrays.sort(a,0,2);
		for (double t:a) {
			System.out.print(t+ " ");
		}
		System.out.println();

		Arrays.sort(a);
		for (double t:a) {
			System.out.print(t+ " ");
		}
		System.out.println();
		sc.close();
	}
}

从大到小

常用方法:
Arrays.sort(数组名,起始下标,终止下标,new cmp() );

cmp函数:

public int compare(Object o1,Object o2)
{
   //降序
	if(o1<o2) return 1;//正数
	else if(o1>o2) return -1;//负数
	else return 0;
	//升序:与上面相反
}

案例(重要,注意看)

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

class cmp implements Comparator<Double>{
	/**
	*<>内是比较的数据类型(封装类/自定义类)
	*如何不写<...>则下面改成:
	**  public int compare((Object o1,(Object o2) {//Object
	**	Double n1=(Double)o1; //强制转化为比较的数据类型
	**	Double n2=(Double)o2; //强制转化为比较的数据类型
	** }
	*/
	public int compare(Double o1,Double o2) {
		if(o1<o2) return 1;
		else if(o1>o2) return -1;
		else return 0;
	}
}
public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Double[] a=new Double[5];//封装类数组/自定义类数组

		for(int i=0;i<5;i++) {
			a[i]=sc.nextDouble();
		}

		Arrays.sort(a, new cmp());//比较

		for (double t:a) {
			System.out.print(t+ " ");
		}
		System.out.println();
		sc.close();
	}
}

自定义类数组排序

方法:同上面从大到小排序
举例:

/*
要求按照枪支的攻击力排序(由大到小),
如果某些枪的攻击力相同则对这些枪按照价格排序(由小到大),
如果某些枪的价格相同则对这些枪按照名字的字典序排列。
(本题中若字符串a,b满足 strcmp(a, b)<0 即满足字典序)
*/
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.*;

class shu /// 创建类
{
	String name;
	int mon;
	int hunt;
}

class cmp implements Comparator<shu> {
	public int compare(shu A, shu B) {
		if (A.hunt == B.hunt) 
		{
			if (A.mon == B.mon) 
			{/************** 按字典序排序*****************/
				int flag = (A.name).compareTo(B.name);
				if (flag == 0)	return 0;
				else if (flag < 0)	return -1;
				else	return 1;
			}
			else 
			{
				if (A.mon == B.mon)	return 0;
				else if (A.mon < B.mon)	return -1;
				else	return 1;
			}
		} 
		else 
		{
			if (A.hunt == B.hunt)return 0;
			else if (A.hunt < B.hunt)	return 1;
			else	return -1;
		}
	}
}

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		shu num[] = new shu[100005];// 创建类数组
		int n = sc.nextInt();
		for (int i = 0; i < n; i++) {
			num[i] = new shu();// 注意这里
			num[i].name = sc.next();
			num[i].hunt = sc.nextInt();
			num[i].mon = sc.nextInt();
		}

		Arrays.sort(num, 0, n, new cmp());// 排序

		for (int i = 0; i < n; i++) {
			System.out.print(num[i].name + " ");
		}
		sc.close();

	}
}
posted @ 2021-11-13 10:07  kingwzun  阅读(333)  评论(0编辑  收藏  举报