标签:php tin sort close 默认 自定义 imp ati targe
?自定义排序格式
///对 num [1,n+1)区间进行自定义排序
Arrays.sort(num,1,n+1,new Comparator<Integer>() { public int compare(Integer o1,Integer o2) { return o1-o2;///o1-o2 : 从小到大排序 } });1 Arrays.sort(num,1,n+1,new Comparator<Integer>() { 2 public int compare(Integer o1,Integer o2) { 3 return o2-o1;///o2-o1 : 从大到小排序 4 } 5 });PS : num 必须是 Integer类型的
?Code
View Code1 package Test; 2 3 import java.util.Arrays; 4 import java.util.Comparator; 5 import java.util.Random; 6 7 public class Sort { 8 9 static Random random = new Random(); 10 public static void main(String[] args) { 11 12 13 Integer[] num = new Integer[10]; 14 15 int n = random.nextInt(5)+5; 16 17 System.out.println("测试默认排序方式"); 18 R(num,n);///随机 n 个数 19 Print(num,n); 20 Arrays.sort(num,1,n+1);///[1,n+1)从小到大排序 21 Print(num,n); 22 System.out.println("+-+-+-+-+-+-+-+-+"+"\n"); 23 24 /* 25 * o1-o2 : 从小到大排序 26 * o2-o1 : 从大到小排序 27 * Math.abs(o2)-Math.abs(o1) : 绝对值从大到小排序 28 */ 29 System.out.println("测试自定义排序方式"); 30 R(num,n); 31 Print(num,n); 32 Arrays.sort(num,1,n+1,new Comparator<Integer>() { 33 public int compare(Integer o1,Integer o2) { 34 return o1-o2;///o1-o2 : 从小到大排序 35 } 36 }); 37 Print(num,n); 38 Arrays.sort(num,1,n+1,new Comparator<Integer>() { 39 40 public int compare(Integer o1,Integer o2) { 41 return o2-o1;///o2-o1 : 从大到小排序 42 } 43 }); 44 Print(num,n); 45 46 System.out.println("+-+-+-+-+-+-+-+-+"+"\n"); 47 } 48 49 public static void R(Integer[] num,int n) { 50 for(int i = 1;i <= n;i++) { 51 num[i] = random.nextInt(20); 52 if(i%2 == 0) 53 num[i] *= -1; 54 } 55 56 } 57 public static void Print(Integer[] num,int n) { 58 for(int i = 1;i <= n;i++) 59 System.out.print(num[i]+" "); 60 System.out.println(); 61 } 62 }
?牛刀小试HDU2020
链接:绝对值排序
?Code
View Code1 import java.util.Arrays; 2 import java.util.Comparator; 3 import java.util.Random; 4 import java.util.Scanner; 5 6 public class Main{ 7 8 static int n; 9 static Integer num[] = new Integer[150]; 10 public static void main(String[] args) { 11 12 Scanner cin = new Scanner(System.in); 13 14 while(cin.hasNext()) { 15 n = cin.nextInt(); 16 if(n == 0) 17 break; 18 19 for(int i = 1;i <= n;i++) { 20 num[i] = cin.nextInt(); 21 } 22 23 Arrays.sort(num,1,n+1,new Comparator<Integer>(){ 24 @Override 25 public int compare(Integer o1, Integer o2) { 26 // TODO Auto-generated method stub 27 return Math.abs(o2)-Math.abs(o1); 28 } 29 30 }); 31 for(int i = 1;i <= n;i++) { 32 if(i != 1) 33 System.out.print(" "); 34 System.out.print(num[i]); 35 } 36 System.out.println(); 37 } 38 } 39 40 }
标签:php tin sort close 默认 自定义 imp ati targe
原文地址:https://www.cnblogs.com/hyacinthLJP/p/14250130.html