本文使用冒泡排序,然后替换了比较方法,可以实现按英文名进行排序,并且当同位上的字母相同时继续比较下一位,主要是利用toCharArray 把字母转化为数字比较大小.也可以把这个方法写javabean中重写的compare方法.
import java.util.*;
public class SortEmployee{
public static class Employee{
private int age;
private String name;
private String dateOfBirth;
Employee(String name) {
this.name=name;
}
}
public static void main(String args[]){
Employee employee[] = new Employee[5];
employee[0] = new Employee("Madison");
employee[1] = new Employee("Ashley");
employee[2] = new Employee("Taylor");
employee[3] = new Employee("Chuck");
employee[4] = new Employee("Brenda");
System.out.println("Order of employee before sorting is");
for(int i=0; i < employee.length; i++) {
System.out.println( employee[i].getName() );
}
// Program Here
int z,j;
for(z=0;z<employee.length-1;z++){
for(j=0;j<employee.length-1-z;j++) {
if(compareString(employee[j].getName(),employee[j+1].getName())){
Employee temp=employee[j];
employee[j]=employee[j+1];
employee[j+1]=temp;
}
}
}
System.out.println("\n\nOrder of employee after sorting by employee name is");
for(int i=0; i < employee.length; i++){
System.out.println( employee[i].getName() );
}
}
public static boolean compareString(String before,String after){
char[] charsBefore = before.toCharArray();
char[] charsAfter = after.toCharArray();
if(before.length()>after.length()){
for (int i =0;i<charsAfter.length;i++){
System.out.print(charsBefore[i]-64);
if((charsAfter[i]-64)<(charsBefore[i]-64)){
return true;
}else if((charsAfter[i]-64)>(charsBefore[i]-64)){
return false;
}
}
return true;
}else{
for (int i =0;i<charsBefore.length;i++){
System.out.print(charsBefore[i]-64);
if((charsBefore[i]-64)>(charsAfter[i]-64)){
return true;
}else if((charsBefore[i]-64)<(charsAfter[i]-64)) {
return false;
}
}
return false;
}
}
}