### 20165334 —— 第十二周MySort(选作)

20165334 —— 第十二周MySort(选作)

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

  1 import java.util.*;
  2
  3 public class MySort1 {
  4     public static void main(String [] args) {
  5         String [] toSort = {"aaa:10:1:1",
  6                             "ccc:30:3:4",
  7                             "bbb:50:4:5",
  8                             "ddd:20:5:3",
  9                             "eee:40:2:20"};
 10
 11         System.out.println("Before sort:");
 12         for (String str: toSort)
 13                     System.out.println(str);
 14
 15         Arrays.sort(toSort);
 16
 17         System.out.println("After sort:");
 18         for( String str : toSort)
 19             System.out.println(str);
 20     }
 21 }

1、首先理解Sort -t : -k 2含义:以“:”为分隔符第二个元素为关键字排序

伪代码

 for (int i = 0; i < toSort.length;i ++){
                     String [] temp = toSort[i].split(":");//以“:”为分隔符提取出其他元素
                     m[i] = Integer.parseInt(temp[1]);//实现存放temp[1]中的数据
           }
           //实现以下效果
           /* i=0 , temp = {aaa , 10 , 1 , 1}
       i=1 , tmp = {ccc , 30 , 3 , 4}
       i=2 , tmp = {bbb , 50 , 4 , 5}
       ....
    */
  //  m = { 10 , 30 , 50 , 40 , 20}
  
if (m[i] == Integer.parseInt((toSort[j].split(":"))[1]))
//匹配toSort[j]以“:”为分隔符的第二个元素

产品代码

/**
 * Created by 李天龙
 */
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 [] m = new int[toSort.length];
                for (int i = 0; i < toSort.length;i ++){
                     String [] temp = toSort[i].split(":");
                     m[i] = Integer.parseInt(temp[1]);//实现存放temp[1]中的数据
           }
           System.out.println("After sort:");
           Arrays.sort(m);
           for (int i = 0 ; i < m.length;i++){
               for (int j = 0 ; j <toSort.length;j++)
                   if (m[i] == Integer.parseInt((toSort[j].split(":"))[1])) {//匹配toSort[j]以“:”为分隔符的第二个元素。
                       System.out.println(toSort[j]);
                    }
                }
              }
           }

运行结果

猜你喜欢

转载自www.cnblogs.com/ltl123/p/9063925.html