以sort降序排列为例:
两种代码写法:
first:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
class node{
int x;
}
class cmp implements Comparator<node>{
@Override
public int compare(node o1, node o2) {//降序
if(o1.x<o2.x) return 1;
else if(o1.x==o2.x) return 0;
else return -1;
}
}
public class 自定义排序 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
node a[]=new node[15];
for(int i=0;i<n;i++){
a[i]=new node();//别忘了new空间
a[i].x=scan.nextInt();
}
Arrays.sort(a,0,n,new cmp());
for(int i=0;i<n;i++){
System.out.println(a[i].x);
}
}
}
second:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
class node implements Comparable<node>{
int x;
@Override
public int compareTo(node o) {
// TODO Auto-generated method stub
if(this.x<o.x) return 1;
else if(this.x==o.x) return 0;
else return -1;
}
}
public class Main{
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
node a[]=new node[15];
for(int i=0;i<n;i++){
a[i]=new node();//别忘了new空间
a[i].x=scan.nextInt();
}
Arrays.sort(a,0,n);
for(int i=0;i<n;i++){
System.out.println(a[i].x);
}
}
}