排序

基础代码:

public class Contact implements Comparable<Contact>{

private String firstName,lastName,phone;

public Contact(String first,String last,String  telephone) {
this.firstName = first;
this.lastName = last;
this.phone = telephone;
}

public String toString() {
return firstName + "--" + lastName + "--" + phone;

}

@Override
public int compareTo(Contact other) {
int  result = 0;
if(lastName.equals(other.lastName))
result = firstName.compareTo(other.firstName);
else
result = lastName.compareTo(other.lastName);
return result;
}

}

public static void main(String[] args) {
Contact[] friends = new Contact[7];
friends[0] = new Contact("John","Smith","123432344");
friends[1] = new Contact("Sarah","Barnes","234532344");
friends[2] = new Contact("Mark","Riley","233432344");
friends[3] = new Contact("Laura","Getz","123443344");
friends[4] = new Contact("Larry","Smith","132432344");
friends[5] = new Contact("Frank","Phelps","323432344");
friends[6] = new Contact("Marsha","Grant","453432344");

for(Contact c : friends) {
System.out.println(c);
}

}

一、选择排序法:

选择排序算法的一般策略如下:扫描整个列表以找出最小值。将这个值与该列表的第一个位置处的值进行交换。扫描(除第一个值)剩余部分列表并找出最小值,然后将它和该列表第二个位置处的值进行交换。扫描(除了前面两个值的)剩余部分列表并找出最小值,然后将它和该列表第三个位置处的值进行交换。对列表中每一个位置继续该过程。当这一过程结束后,列表也就排好序了。

实现代码:

public static <T extends Comparable<? super T>> void selectionSort ( T[]  data ) {
int min;
T temp;
for(int index=0; index<data.length-1; index++) {
min = index;
//获取值最小的下标
for( int scan=index+1 ; scan<data.length ; scan++) {
if(data[scan].compareTo(data[min])<0) {
min = scan;
}
}
//交换位置
temp = data[index];
data[index] = data[min];
data[min] = temp;
}

}

二、插入排序:

插入排序的一般策略如下,对列表中的头两个值依据其相对大小对其进行排序;将列表中的第三个值插入到头两个(以排序的)值中的恰当位置。然后将第四个值插入到列表头三个值的正确位置。每做出一次插入,该排序子集中的值数目就会增加一个,继续这一过程,直至列表中的所有元素都完全排序。该插入过程需要对数组中的其它元素移位,以给插入元素腾出空间。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值