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