20175214 MySort(選作)

1、題目要求

  • 模擬實現Linux下Sort -t : -k 2的功能。
  • 要有僞代碼,產品代碼,測試代碼(注意測試用例的設計)
  • 參考 Sort的實現。提交博客連接。

2、設計思路

  • 在命令行中輸入須要的參數;
  • 使用split方法將每一行分解得到須要的可供排序的數組;
  • 對得到的數組排序;
  • 將排序後的數組輸出。

3、代碼實現

  • 僞代碼:java

    • 輸出排序前的數組;
    • 命令行輸入參數;
    • 判斷參數是否符合要求;
    • 對排序好的數組遍歷並輸出第二列元素相同的toSort數組。
  • 產品代碼:git

    import java.util.*;
    public class MySort {
     public void mySort(String[] toSort, int k) {
         System.out.println("Before sort:");
         for (String str : toSort) {
             System.out.println(str);
         }
         int length = toSort.length;
         int[] a = new int[length];
         if (k == 1) {
             for (int i = 0; i < length; i++) {
                 a[i] = Integer.parseInt(toSort[i].split(":")[k]);
             }
         }
         Arrays.sort(a);
         System.out.println("After sort:");
         for (int i = 0; i < length; i++) {
             for (int j = 0; j < length; j++) {
                 if (a[i] == Integer.parseInt(toSort[j].split(":")[k])) {
                     System.out.println(toSort[j]);
                 }
             }
         }
     }
    }
  • 測試代碼:數組

    public class MySortTest {
     public static void main(String[] args) {
         String[] toSort = {"aaa:10:1:1",
                 "ccc:30:3:4",
                 "bbb:50:4:5",
                 "ddd:20:5:3",
                 "eee:40:2:20"};
         int a = Integer.parseInt(args[0]);
         MySort mysort = new MySort();
         mysort.mySort(toSort, a);
     }
    }

4、測試結果截圖

5、碼雲連接

碼雲連接測試

相關文章
相關標籤/搜索