Java印製排序演算法比較分析表格 === ###### tags: `程式設計` `JAVA` `資訊工程` :::info _適用於排序法的表格_ 來印製出漂亮的表格吧~ ٩(๑❛ᴗ❛๑)۶ ::: ## SourceCode *Tables.java* ```java //package src.algorithm; public class Tables{ private String[] method; private double[] fast; private double[] slow; private double[] avg; private int volume; private int count = 16; /********************************************************************* * @param method 排序法名稱 * @param fast 最快速度 * @param slow 最慢速度 * @param avg 平均值 * @param volume 測試樣本數量 *********************************************************************/ public Tables(String[] method, double[] fast, double[] slow, double[] avg, int volume){ this.method=method; this.fast=fast; this.slow=slow; this.avg=avg; this.volume=volume; } /*********************************************************************/ // 印製表格 public void print() { // 計算表格的寬度 int width = 18; width+=count*method.length; // 印出表格上方的分隔線 System.out.println("+" + "-".repeat(width-2) + "+"); /*********************************************************************/ // 印出表格標題 System.out.printf("| %-13s |", "next(n)"); for (String m : method) System.out.printf(" %-7s |", m); System.out.println(); /*********************************************************************/ // 印出表格中間的分隔線 System.out.println("+" + "-".repeat(width-2) + "+"); /*********************************************************************/ // 印出表格內容 System.out.printf("| %13s |", "Fastest"); for (double f : fast) System.out.printf(" %12.4f |", f); System.out.println(); System.out.printf("| %-4d %9s |", volume , "Slowest"); for (double s : slow) System.out.printf(" %12.4f |", s); System.out.println(); System.out.printf("| %13s |", "Average"); for (double a : avg) System.out.printf(" %12.4f |", a); System.out.println(); /*********************************************************************/ // 印出表格下方的分隔線 System.out.println("+" + "-".repeat(width-2) + "+"); } } ``` **Output**: ```md +-----------------------------------------------------+ | next(n) | 插入排序法 | 氣泡排序法 | 合併排序法 | +-----------------------------------------------------+ | Fastest | 0.0040 | 0.0410 | 0.0000 | | 50 Slowest | 0.0270 | 0.0670 | 0.0040 | | Average | 0.0052 | 0.0456 | 0.0009 | +-----------------------------------------------------+ ``` **Example**: _Demo.java_ ```java= //package src.algorithm; public class Demo { public static void main(String[] args) { String[] SortList = { "插入排序法" , "泡沫排序法" , "合併排序法" }; double[] fast= { 5.5 , 6.6 , 7.7 }; double[] slow = { 9.9 , 10.10 , 11.11 }; double[] avg = { 4.4 , 5.5 , 6.6 }; int volume = 500; Tables test = new Tables(SortList, fast, slow, avg, volume); test.print(); } } ``` _上面的數值可以用其他方式去喂入_