2015-team4/java文件输入输出和标号排序
从 Trac 迁移的文章
这是从旧校内 Wiki 迁移的文章,可能存在一些样式问题,您可以向 memset0 反馈。
原文章内容如下:
{{{
import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
public class Main {
static final int MAXN = 1000;
static int a[] = new int[MAXN];
static Integer idx[] = new Integer[MAXN];/* 默认升序,如果要自定cmp函数,待排序的数组里的值应该是Integer等对象,不能是int等基本类型 */
public static void main(String[] args) throws FileNotFoundException{
Scanner sc = new Scanner(new File("a.in"));
PrintWriter out = new PrintWriter("a.out");
int n = sc.nextInt();
for(int i = 0; i < n; i++) a[i] = sc.nextInt();
for(int i = 0; i < n; i++) idx[i] = i;
Arrays.sort(idx, 0, n, new Cmp()); /* 类似sort(idx, idx + n, cmp) */
for(int i = 0; i < n; i++) out.print(a[idx[i]]+" ");
out.println();
out.close(); /* 一定要记得关闭文件, 不然可能没输出*/
sc.close();
}
static class Cmp implements Comparator<Integer> {
public int compare(Integer x, Integer y){ /* 实现compare方法 */
return a[x] - a[y]; /* 返回负数为小于 */
}
}
}
}}}
import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
public class Main {
static final int MAXN = 1000;
static int a[] = new int[MAXN];
static Integer idx[] = new Integer[MAXN];/* 默认升序,如果要自定cmp函数,待排序的数组里的值应该是Integer等对象,不能是int等基本类型 */
public static void main(String[] args) throws FileNotFoundException{
Scanner sc = new Scanner(new File("a.in"));
PrintWriter out = new PrintWriter("a.out");
int n = sc.nextInt();
for(int i = 0; i < n; i++) a[i] = sc.nextInt();
for(int i = 0; i < n; i++) idx[i] = i;
Arrays.sort(idx, 0, n, new Cmp()); /* 类似sort(idx, idx + n, cmp) */
for(int i = 0; i < n; i++) out.print(a[idx[i]]+" ");
out.println();
out.close(); /* 一定要记得关闭文件, 不然可能没输出*/
sc.close();
}
static class Cmp implements Comparator<Integer> {
public int compare(Integer x, Integer y){ /* 实现compare方法 */
return a[x] - a[y]; /* 返回负数为小于 */
}
}
}