6-2 对Person信息排序 (50 分)
Person包括3个字段:身份证号(id),姓名(name),年龄(age)。 先输入一个正整数N,后续输入N个Person的信息。 输出结果为按id从小到大的排序结果。
注:可使用冒泡法对数组进行排序,也可使用集合。
import java.util.*;
class Person {
private int age;
private String name;
private String id;
public Person(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
final int N = Integer.parseInt(sc.nextLine());
Person[] persons = new Person[N];
// 读入N个学生的信息:id, name, age
for(int i=0; i<N; i++) {
String str = sc.nextLine();
String[] strs = str.split(" ");
persons[i] = new Person(strs[0], strs[1], Integer.parseInt(strs[2]));
}
sc.close();
// 排序
sort(persons);
for(Person p: persons) {
System.out.println(p.getId() + ", " + p.getName() + ", " + p.getAge());
}
}
/* 你的答案将复制到这里*/
}
集合法
方法一:
public static void sort(Person[] persons) {
Person t;
ArrayList<String> sites = new ArrayList<>();//动态数组
for(int i=0; i<persons.length; i++) {
sites.add(persons[i].getId());
}
sites.sort(Comparator.naturalOrder()); //动态数组顺序
String[] arr = new String[sites.size()];
sites.toArray(arr);//动态数组 转 静态
for (int i=0;i<persons.length;i++) {
for(int j=0;j<persons.length;j++) {
if(arr[i]==persons[j].getId())
{
t=persons[i];
persons[i]=persons[j];
persons[j]=t;
}
}
}
冒泡法
-
方法二: public static void sort(Person[] persons) { for(int i = 0;i < persons.length; i++){ for(int j = 0; j < persons.length-i-1; j++){ if(persons[j].getId().compareTo(persons[j+1].getId()) > 0){ Person temp1 = persons[j]; persons[j] = persons[j+1]; persons[j+1] = temp1; } } } }