java:sort

SORT

普通数组排序

public class Main {
	public static int n;
	public static int N = 100005;
	public static int a[] = new int[N];
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		for(int i = 1; i <= n; i++) {
			a[i] = sc.nextInt();
		}
		Arrays.sort(a, 1, n + 1);
		for(int i = 1; i <= n; i++) {
			if(i > 1) System.out.print(" ");
			System.out.print(a[i]);
		}
	}
}

cmp实现从大到小排序(也可以正向排序,倒着输出就行)

class shu {
	int x;
}
class cmp implements Comparator<shu> {
	public int compare(shu A, shu B) {
		return B.x - A.x; // 按从大到小排序
	}
}
public class Main {
	public static int n;
	public static int N = 100005;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		shu a[] = new shu[N]; // 创建类数组
		for(int i = 1; i <= n; i++) {
			a[i] = new shu(); // 初始化,实例化
			a[i].x = sc.nextInt();
		}
		Arrays.sort(a, 1, n + 1, new cmp());
		for(int i = 1; i <= n; i++) {
			if(i > 1) System.out.print(" ");
			System.out.print(a[i].x);
		}
	}
}

多个值排序:score不同,则按score从大到小排序;如果score相同,就按string的字典序排序。

class node {
	String name;
	int score;
}
class cmp implements Comparator<node> {
	public int compare(node A, node B) {
		if(A.score != B.score) {
			return B.score - A.score; // 分数从高到低
		} else {
			return A.name.compareTo(B.name); // 字典序从小到大
		}
	}
}

补充:不同类型数组长度的区别,结果如下图。

public class practice {
	static Scanner sc = new Scanner(System.in);
	static int N = 1005;
	static int a[] = new int[N];
	static double b[] = new double[N];
	static float c[] = new float[N];
	static char s[] = new char[N];
	public static void main(String[] args) {
		System.out.println("int型的数组长度:" + a.length);
		System.out.println("double型的数组长度:" + b.length);
		System.out.println("float型的数组长度:" + c.length);
		String str = new String(sc.next());
		s = str.toCharArray();
		System.out.println("char型的数组长度:" + s.length);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值