排序_简单排序_插入排序_对象的排序

public class Person {
    private String lastName;
    private String firstName;
    private int age;
    public Person(String last,String first,int a) {
        lastName=last;
        firstName=first;
        age=a;
    }
    public void displayPerson() {
        System.out.print("last name:"+lastName);
        System.out.print(",first name"+firstName);
        System.out.println(",age:"+age);
    }
    public String getLast() {
        return lastName;
    }

}
public class ArrayInOb {
    private Person a[];
    private int nElems;
    public ArrayInOb(int maxSize) {
        a=new Person[maxSize];
        nElems=0;
    }
    //插入
    public void insert(String last,String first,int age) {        
        a[nElems++]=new Person(last, first, age);
    }
    //显示
    public void display() {
        for(int j=0;j<nElems;j++)
            a[j].displayPerson();
        System.out.println();
    }
    //排序
    public void insertionSort() {
        int out,in;
        for(out=1;out<nElems;out++) {
            Person temp=a[out];
            in=out;
            //对姓进行排序
            while(in>0 && a[in-1].getLast().compareTo(temp.getLast())>0) {
                a[in]=a[in-1];
                in--;
            }
            a[in]=temp;
        }
    }

}
public class Test {

    public static void main(String[] args) {
        int maxSize=100;
        ArrayInOb array=new ArrayInOb(maxSize);
        array.insert("Evans", "Patty", 24);
        array.insert("Smith", "Lorraine", 37);
        array.insert("Smith", "Tom", 43);
        array.insert("Smith", "Henry", 63);
        array.insert("Yee", "Sato", 21);
        array.insert("Hashimoto", "Henry", 29);
        array.insert("Stimson", "ming", 72);
        array.insert("Velasquez", "rong",54 );
        array.insert("Vang", "qian", 22);
        array.display();
    
        array.insertionSort();
        array.display();

    }

}

 

posted @ 2017-12-24 10:13  S-Mustard  阅读(219)  评论(0编辑  收藏  举报