//Driver for testing a sorting algorithm.
public class PhoneList {
public static void main(String[] args){
Contact[]friends=new Contact[5];
friends [0]=new Contact("John","Smith","620-555-7384");
friends [1]=new Contact("Sarah","Barnes","215-555-3827");
friends[2]=new Contact("Mark","Riley","733-555-2969");
friends[3]=new Contact("Laura","Getz","663-555-3984");
friends[4]=new Contact("Larry","Smith","464-555-3489");
Sorting.selectionSort(friends);
for(Contact friend :friends)
System.out.println(friend);
}
}
//Demonstrates the selection sort and insertion sort algorithms.
public class Sorting {
public static void selectionSort(Comparable []list){
int min;
Comparable temp;
for (int index=0;index<list.length-1;index++){
min=index;
for(int scan=index+1;scan<list.length;scan++)
if(list[scan].compareTo(list[min])<0)
min=scan;
temp=list[min];
list[min]=list[index];
list[index]=temp;
}
}
public static void insertionSort(Comparable[]list){
for(int index=1;index<list.length;index++){
Comparable key=list[index];
int position=index;
while(position>0&&key.compareTo(list[position-1])<0)
{
list[position]=list[position-1];
position--;
}
list[position]=key;
}
}}
//Represents a phone contact.
public class Contact implements Comparable{
private String firstName,lastName,phone;
public Contact(String first,String last,String telephone){
firstName=first;
lastName=last;
phone=telephone;
}
public String toString(){
return lastName+", "+firstName+"\t"+phone;
}
public boolean equals(Object other){
return (lastName.equals(((Contact)other).getLastName())&&firstName.equals(((Contact)other
).getFirstName()));
}
public int compareTo(Object other){
int result;
String otherFirst=((Contact)other).getFirstName();
String otherLast=((Contact)other).getLastName();
if(lastName.equals(otherLast))
result=firstName.compareTo(otherFirst);
else
result=lastName.compareTo(otherLast);
return result;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
}
转载于:https://my.oschina.net/yanjianhai/blog/133241