• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
苍穹之下,铁幕之后
博客园    首页    新随笔    联系   管理    订阅  订阅

20155228 2017-5-10 课堂测试:MySort

20155228 2017-5-10 课堂测试:MySort

题目和要求

模拟实现Linux下Sort-t:-k2的功能。参考Sort的实现。提交码云链接和代码运行截图。

import java.util.*;
public class MySort1 {
    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);
    }
}

分析和设计

Sort-t:-k2的作用是以:为间隔,第二部分内容进行比较,从小到大进行排序的过程。

1.使用for循环把4个字符串进行切割
toSort[i].split(":")
2.每个字符串被切割成4部分,取第二部分字符串数据转换成int类型数据
Integer.parseInt(toSort[i].split(":")[1])
3.把int类型数据放入tmp数组中
Integer [] tmp = new Integer [toSort.length];
for(int i=0; i<tmp.length; i++)
    tmp[i] = new Integer(Integer.parseInt(toSort[i].split(":")[3]);
4.对tmp进行排序
 Arrays.sort(tmp);

问题和解决

  • 对tmp进行排序之后然后根据tmp的数据进行输出,主要的思路是,分别考察tmp中每个元素与哪个字符串中元素相符,首先是tmp中第一个元素,依次将4个字符串的内容与第一个元素进行比较,相同就打印字符串,然后是tmp中第二个元素,以此类推,这样根据打印出来就是满足需要的结果。

代码和结果

  • 运行截图

  • 代码链接
posted @ 2017-05-10 11:45  Besti20155228  阅读(203)  评论(1)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3