MySort的实现

一、实验要求

研究sort的其他功能,要能改的动代码,模拟实现Linux下Sort -t : -k 2的功能。

二、代码

/**
* Created by xiang on 2018/5/17.
*/
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); System.out.println("After sort:");
int[] s = new int[toSort.length];
String[][] string = new String [toSort.length][4];
for (int i = 0; i < toSort.length; i++) {
string[i] = toSort[i].split(":");
s[i] = Integer.parseInt(string[i][1]);
}
Arrays.sort(s);
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < toSort.length; j++) {
if(s[i] == Integer.parseInt(string[j][1])){
System.out.println(toSort[j]);
}
}
}
}
}

三、运行结果

20165226 MySort的实现-LMLPHP

四、测试

20165226 MySort的实现-LMLPHP

五、总结

sort实验中最关键的是 string[i] = toSort[i].split(":"); s[i] = Integer.parseInt(string[i][1]);

用冒号作为间隔符,并针对第二列来进行数值升序排序。

05-01 06:48