MySort选做

一、题目要求

(1)模拟实现Linux下Sort -t : -k 2的功能;
(2)要有伪代码,产品代码,测试代码(注意测试用例的设计);
(3)参考 Sort的实现。提交博客链接。
需要补充的代码:

 import java.util.*;
  
   public class MySort {
       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"};
 
          System.out.println("Before sort:");
          for (String str: toSort)
                      System.out.println(str);
 
          Arrays.sort(toSort);
 
         System.out.println("After sort:");
          for( String str : toSort)
              System.out.println(str);
      }
 }

二、设计思路

(1)在命令行中输入需要的参数;
(2)使用split方法将每一行分解获得需要的可供排序的数组;
(3)对获得的数组排序;
(4)将排序后的数组输出。

三、代码实现

(1)伪代码:

输出排序前的数组;
命令行输入参数;
判断参数是否符合要求;
对排序好的数组遍历并输出第二列元素相同的toSort数组。

(2)产品代码:

import java.util.*;

public class MySort {
    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"};

        System.out.println("Before sort:");
        for (String str: toSort) {
            System.out.println(str);
        }
        int [] a = new int[toSort.length];
        for (int i = 0; i < toSort.length; i++){
            String [] tmp = toSort[i].split(":");
            a[i] = Integer.parseInt(tmp[1]);
        }
        Arrays.sort(a);
        System.out.println("After sort:");
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < toSort.length; j++) {
                if (a[i] == Integer.parseInt((toSort[j].split(":"))[1])) {
                    System.out.println(toSort[j]);
                }
            }
        }
    }
}

四、测试截图

五、码云链接

https://gitee.com/zzm-zcc/zhang_zhi_min/commit/79ab6818c82ae112006924231351d44643b57c00

原文地址:https://www.cnblogs.com/zzmzcc/p/10890194.html