計數演算法-對200萬考生的成績就行排序
阿新 • • 發佈:2021-06-24
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); } }