对象排序简单小例子

public class ObjectSort {
Person[] persons = null;
int max =0;
int count = 0;



public ObjectSort(int max) {
this.persons = new Person[max];
this.max = max;
}

public void insertPerson(Person person){
if(count<max){
persons[count] = person;
count++;
}
}

public void insertSort(){
//使用插入排序
for(int i=1;i<count;i++){
Person temp = persons[i];
int index = i;
while(index-1>=0&&temp.getLastName().compareTo(persons[index-1].getLastName())<0){
persons[index] = persons[index-1];
index--;
}
persons[index] = temp;
}

}
public void bubbleSort(){
//冒泡
for(int i=count;i>0;i--){
for(int j=0;j<i-1;j++){
if(this.compareMAX(persons[j], persons[j+1])){
wrap(j,j+1);
}
}
}
}

public void selectSort(){
int min;
for(int i=0;i<count-1;i++){
min = i;
for(int j=i+1;j<count;j++){
if(this.compareMIN(persons[j], persons[min])){
min = j;
}
}
wrap(i,min);
}
}
// one>aim
private boolean compareMAX(Person one,Person aimOne){
return one.getLastName().compareTo(aimOne.getLastName())>0;
}
// one<aim
private boolean compareMIN(Person one,Person aimOne){
return one.getLastName().compareTo(aimOne.getLastName())<0;
}
private void wrap(int i,int j){
Person temp = persons[j];
persons[j] = persons[i];
persons[i] = temp;

}
public void displayPerson(){
for(int i=0;i<count;i++){
System.out.println(persons[i]);
}
}

public static void main(String[] args){
ObjectSort obj = new ObjectSort(5);
obj.insertPerson(new Person("1","D"));
obj.insertPerson(new Person("2","B"));
obj.insertPerson(new Person("3","A"));
obj.insertPerson(new Person("4","C"));
obj.insertPerson(new Person("5","E"));
obj.insertPerson(new Person("6","F"));
System.out.println("======原始===========");
obj.displayPerson();
System.out.println("======插入===========");
obj.insertSort();
obj.displayPerson();
System.out.println("======冒泡===========");
obj.bubbleSort();
obj.displayPerson();
System.out.println("=======选择==========");
obj.selectSort();
obj.displayPerson();
}
}
class Person{
private String firstName;
private String lastName;

public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String toString(){
return this.lastName+"\t"+this.firstName;
}

}

你可能感兴趣的:(C++,c,C#,F#,J#)