程序实现自动生成1000万个从1000万到1亿之间的随机数写入到文件中,然后对这些数进行从小到大排序写入到新的文件中。
核心思想:用一个很大的数组来记录随机数出现的次数,然后直接输出这个基数器的序号即为排序结果。
private static final int SIZE = 10000000;//随机数数量
private static final int START = 10000000;//随机数开始值
private static final int END = 89999999;//随机数增量
private static final String DIR = "e:/test/";
public static void main(String[] args) throws Exception{
long time = System.currentTimeMillis();
createTestData();
System.out.println("耗时:"+(System.currentTimeMillis() - time));
time = System.currentTimeMillis();
sort();
System.out.println("耗时:"+(System.currentTimeMillis() - time));
System.out.println("完成!");
}
private static void sort()throws Exception{
System.out.println("初始化排序数组...");
int[] record = new int[END+1];
for(int i = 0;i<record.length;i++){
record[i] = 0;
}
File file = new File(DIR+"test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine())!=null){
record[Integer.parseInt(line) - START] += 1;
}
br.close();
System.out.println("正在排序...");
File file2 = new File(DIR+"test-result.txt");
if(!file.exists()){
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file2,true));
int i = START;
for(int r : record){
if(r>=1){
for(int j = r;j>0;j--){
bw.write(i+(r>1?" <---":""));
bw.newLine();
}
}
i++;
//System.out.println("i="+i);
}
bw.close();
}
private static void createTestData()throws Exception{
Random r = new Random();
File file = new File(DIR+"test.txt");
if(!file.exists()){
file.createNewFile();
}
System.out.println("正在生成随机数...");
BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
for(int i = 0;i<SIZE;i++){
bw.write(START+r.nextInt(END)+"");
bw.newLine();
//System.out.println("i="+i);
}
bw.close();
}