几种排序算法


public class App {

public static void main(String[] args) {

int[] data = { 1, 3, 2, 9, 5, 10, 23 };

System.out.println("from:"+Arrays.toString(data));

List<Sort> sortList = new ArrayList<Sort>();
sortList.add(new InsertionSort());
sortList.add(new SelectionSort());
sortList.add(new InsertionSort());

for (Sort sort : sortList) {
data = sort.sort(data);
System.out.println(sort.getClass().getSimpleName() + ":"+ Arrays.toString(data));
}


}

}



from:[1, 3, 2, 9, 5, 10, 23]
InsertionSort:[1, 2, 3, 5, 9, 10, 23]
SelectionSort:[1, 2, 3, 5, 9, 10, 23]
InsertionSort:[1, 2, 3, 5, 9, 10, 23]



package com.tempus.px;

/*

-------------------插入排序算法--------------------
从第一个位子开始,后面的数字插入到前面的一个适当的位置

*/
public class InsertionSort implements Sort {

public int[] sort(int[] data) {

if (data != null) {

for (int i = 1; i < data.length; i++) {
int temp = data[i];
int j = i;

while (data[j - 1] > temp && j>0) {
data[j] = data[j - 1];// 大数往后移一个位子
j--;

}
data[j] = temp;
}
}
return data;
}

}






package com.tempus.px;


/*
------------------选择排序算法--------------------
与冒泡法排序很相似,从第一个位子开始,与后面的比较取最小,
每次比较记录最小值的位置,最后将最小值的位置的数与当前位置的数对换,只对换一次
*/


public class SelectionSort implements Sort {


public int[] sort(int[] data){

if(data!=null){
int min;
int minLocal;
for(int i=0;i<data.length;i++){
min=data[i];
minLocal=i;
for(int j =i+1;j<data.length;j++){
if(min>data[j]){
minLocal=j;
min=data[j];
}
}

if(minLocal!=i){
int tmp=data[i];
data[i]=data[minLocal];
data[minLocal]=tmp;
}
}
}
return data;
}

}




package com.tempus.px;

/*

-------------------插入排序算法--------------------
从第一个位子开始,后面的数字插入到前面的一个适当的位置

*/
public class InsertionSort implements Sort {

public int[] sort(int[] data) {

if (data != null) {

for (int i = 1; i < data.length; i++) {
int temp = data[i];
int j = i;

while (data[j - 1] > temp && j>0) {
data[j] = data[j - 1];//在数往后移一个位子
j--;

}
data[j] = temp;
}
}
return data;
}

}



[url]http://blog.csdn.net/fenglibing/article/details/1756473[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值