`

折半插入排序

阅读更多
没事,写写算法!
这个算法是:折半插入排序

1、Data类,要排序的对象:
package sort.cy.BinaryInsertSort;

public class Data {
private int data;

public int getData() {
return data;
}

public void setData(int data) {
this.data = data;
}
public Data(int data){
this.data = data;
}
}

2、CyBinaryInsertSort 类,对Data类进行排序:

package sort.cy.BinaryInsertSort;

import java.util.ArrayList;

public class CyBinaryInsertSort {
private ArrayList<Data> list;
public CyBinaryInsertSort(){
list = new ArrayList<Data>();
}
public void addData(Data data){
list.add(data);
}

private void validate(){
if(3 > list.size()){
System.out.println("白痴吧,这么简单~");
System.exit(0);
}
}
public void sort(){
this.validate();//验证合法性

for(int i=1; i<list.size(); i++){
int low = 0;
int high = i-1;
int mid = 0;
Data data= list.get(i);

while(low <= high){
//找到相应的位置
mid = (low + high) / 2;
if(list.get(i).getData() >= list.get(mid).getData()){
low = mid + 1;
}
else{
high = mid - 1;
}
}

for(int j=i; j>high+1; j--){
// 移动 。
list.set(j, list.get(j-1));
System.out.println("move " + j);

}
list.set(high+1, data);
System.out.println("move " + i);

}

}
public void print(){

for(int i=0; i<list.size(); i++){
System.out.println(list.get(i).getData());
}

}

}


3、Main 主函数 测试:

package sort.cy.BinaryInsertSort;

public class MainTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
CyBinaryInsertSort cy = new CyBinaryInsertSort();
cy.addData(new Data(66));
cy.addData(new Data(3));
cy.addData(new Data(4));
cy.addData(new Data(1));
cy.addData(new Data(9));
cy.addData(new Data(3));
cy.addData(new Data(4));
cy.addData(new Data(1));
cy.addData(new Data(9));
cy.sort();
cy.print();
}

}

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics