Skip to content

Instantly share code, notes, and snippets.

@charleehu
Created December 2, 2011 11:44
Show Gist options
  • Save charleehu/1422955 to your computer and use it in GitHub Desktop.
Save charleehu/1422955 to your computer and use it in GitHub Desktop.
编程珠玑-chapter1-磁盘文件排序
public class FileBitSort {
public static void generateData(String path, int max) throws Exception {
File f = new File(path);
if (f.exists()) {
f.delete();
} else {
f.createNewFile();
}
List<Long> data = new ArrayList<Long>();
for (long i = 0; i < max; i++) {
data.add(i);
}
Collections.shuffle(data);
PrintWriter pw = null;
try {
pw = new PrintWriter(f);
for (Long d : data) {
pw.println(d);
}
} finally {
if (pw != null) pw.close();
}
}
public static void sort(String input, String output, int num) throws Exception {
long step1 = System.currentTimeMillis();
//step 1: init
byte[] data = new byte[num];
System.out.println("init cost: " + (System.currentTimeMillis() - step1));
long step2 = System.currentTimeMillis();
//step 2: input
BufferedReader sc = null;
try {
sc = new BufferedReader(new FileReader(input));
String r = null;
while ((r = sc.readLine()) != null) {
data[Integer.parseInt(r)] = 1;
}
} finally {
if (sc != null) sc.close();
}
System.out.println("input cost: " + (System.currentTimeMillis() - step2));
long step3 = System.currentTimeMillis();
//step 3: output
PrintWriter pw = null;
try {
pw = new PrintWriter(output);
for (int i = 0; i < data.length; i++) {
if (data[i] == 1) pw.println(i);
}
} finally {
if (pw != null) pw.close();
}
System.out.println("output cost: " + (System.currentTimeMillis() - step3));
}
public static void main(String[] args) throws Exception {
//generateData("c:/data.txt", 10000000);
sort("c:/data.txt", "c:/data_1.txt", 10000000);
}
}
init cost: 16
input cost: 3312
output cost: 3328
注:step2使用Scanner时性能较差。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment