selection and insertion sort algorithms

//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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值