插入排序之Shell排序(java实现)
import java.util.Arrays;
public class ShellSort {public static void shellSort(DataWraper[] data){
System.out.println("开始排序:");
int arrayLength=data.length;
int h=1;
//按h*3+1得到增量序列的最大值
while(h<arrayLength/3){
h=h*3+1;
}
while(h>0){
System.out.println("====h的值:"+h+"===");
for(int i=h;i<arrayLength;i++){
DataWraper tmp=data[i];
if(data[i].compareTo(data[i-h])<0){
int j=i-h;
for(;j>=0&&data[j].compareTo(tmp)>0;j-=h){
data[j+h]=data[j];
}
data[j+h]=tmp;
}
System.out.println(Arrays.toString(data));
}
h=(h-1)/3;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DataWraper [] data={
new DataWraper(21, ""),
new DataWraper(30, ""),
new DataWraper(49, ""),
new DataWraper(30, "*"),
new DataWraper(16, ""),
new DataWraper(9, ""),
new DataWraper(-16, ""),
new DataWraper(10, ""),
};
System.out.println("排序之前:\n"+Arrays.toString(data));
shellSort(data);
System.out.println("排序之后:\n"+Arrays.toString(data));
}}
结果:
排序之前:
[21, 30, 49, 30*, 16, 9, -16, 10]
开始排序:
====h的值:4===
[16, 30, 49, 30*, 21, 9, -16, 10]
[16, 9, 49, 30*, 21, 30, -16, 10]
[16, 9, -16, 30*, 21, 30, 49, 10]
[16, 9, -16, 10, 21, 30, 49, 30*]
====h的值:1===
[9, 16, -16, 10, 21, 30, 49, 30*]
[-16, 9, 16, 10, 21, 30, 49, 30*]
[-16, 9, 10, 16, 21, 30, 49, 30*]
[-16, 9, 10, 16, 21, 30, 49, 30*]
[-16, 9, 10, 16, 21, 30, 49, 30*]
[-16, 9, 10, 16, 21, 30, 49, 30*]
[-16, 9, 10, 16, 21, 30, 30*, 49]
排序之后:
[-16, 9, 10, 16, 21, 30, 30*, 49]