SORT
Ordinary Sorting an array
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 realize descending order (can also be sorted forward, backwards output on the line)
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);
}
}
}
Sorting the plurality of values: different score, score press descending order; if the same score, to press the string lexicographically sorted.
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); // 字典序从小到大
}
}
}
NOTE: distinguish between different types of array length, results as shown below.
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);
}
}