跟插入排序一样,不过比较的是对象的某一个变量
public class ObjectSort {
public static void display(List<Person> array){
for(int i=0;i<array.size();i++){
Person person = array.get(i);
System.out.println(person.getFirstName()+" "+person.getLastName()+" age:"+person.getAge());
}
System.out.println();
}
public static void sort(List<Person> array){
for(int i=1;i<array.size();i++){
Person tmp = array.get(i);
int minIndex = i;
for(int j=i-1;j>=0;j--){
if(tmp.getLastName().compareTo(array.get(j).getLastName())<0){
array.set(j+1,array.get(j));
minIndex = j;
}
}
if(minIndex!=i){
array.set(minIndex,tmp);
}
}
}
public static void main(String[] args){
List<Person> array = new ArrayList<Person>();
Person person = new Person("Evans","patty",24);
array.add(person);
person = new Person("Smith","Doc",59);
array.add(person);
person = new Person("Smith","Lorraine",37);
array.add(person);
person = new Person("Smith","Paul",37);
array.add(person);
person = new Person("Yee","Tom",43);
array.add(person);
person = new Person("Hashimoto","Sato",21);
array.add(person);
person = new Person("Stimson","Henry",29);
array.add(person);
person = new Person("Velasquez","Jose",72);
array.add(person);
person = new Person("Vang","Minh",22);
array.add(person);
person = new Person("Creswell","Lucinda",18);
array.add(person);
display(array);
sort(array);
display(array);
}
}
原文:http://www.cnblogs.com/ajfajz/p/7272950.html