import java.io.*;
import java.text.DecimalFormat;
/**
* @author: small sunshine
* @Description:
* @date: 2021/6/20 10:04 上午
*/
public class ScoreDescSort {
private static long length = 200 * 10000;
private static int[] score = new int[200 * 10000];
private static int[] scoreCopy = new int[750 * 100 + 1];
private static File file = new File("/Users/lizhenguang/Desktop/score.txt");
private static File fileCopy = new File("/Users/lizhenguang/Desktop/score_copy.txt");
/**
* 对200万考生的分数(保留两位小数)倒序排列
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
createFile(length);
createArray();
flushArray();
printResult();
long end = System.currentTimeMillis();
System.out.println("操作总用时:" + (end - start) + "ms");
}
/**
* 1、创建分数文件
*
* @param length
* @throws IOException
*/
public static void createFile(long length) throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
for (int i = 0; i < length; i++) {
if (i != 0) {
bufferedWriter.newLine();
}
bufferedWriter.write(doubleFormat(Math.random() * 750));
}
bufferedWriter.flush();
outputStreamWriter.flush();
bufferedWriter.close();
outputStreamWriter.close();
}
/**
* 从文件中读分数并写入到数组中
*
* @throws IOException
*/
public static void createArray() throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String scores = null;
int index = 0;
while ((scores = bufferedReader.readLine()) != null) {
score[index++] = (int) (Double.valueOf(scores) * 100);
}
bufferedReader.close();
inputStreamReader.close();
}
/**
* 计数法处理分数
*/
public static void flushArray() {
for (int i: score) {
scoreCopy[i]++;
}
}
/**
* 排好序并打印出来
*
* @throws IOException
*/
public static void printResult() throws IOException{
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(fileCopy), "UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
for (int j = scoreCopy.length - 1; j >= 0; j--) {
if (scoreCopy[j] > 0) {
for (int z = 0; z < scoreCopy[j]; z++) {
bufferedWriter.write(doubleFormat((j / 100D)) + "");
bufferedWriter.newLine();
}
}
}
bufferedWriter.flush();
outputStreamWriter.flush();
bufferedWriter.close();
outputStreamWriter.close();
}
/**
* 随机分数-格式化:#.##
*
* @param in
* @return
*/
public static String doubleFormat(double in) {
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.applyPattern("0.00");
return decimalFormat.format(in);
}
}
原文:https://www.cnblogs.com/Small-sunshine/p/14926398.html