最近一在校的校友求助哥们来一个希尔排序的JAVA版本实现,
好久没碰了,话费了一个小时搞定一个贴在下面,希望对有兴趣的同学有所帮助。
public class ShellSort {
public static int[] a = {29,1,59,12,4,77,40,20,15,10,44,8,81,0,8,13,16};
public static void main(String[] args) {
//设置循环 - 步长 - 间隔
for (int m = a.length / 2 ; m > 0; m = m/2) {
//根据步长确定需要排序的数组下标索引
for (int n=0; n < a.length; n = n + m) {
//对特定数组索引构成的数组进行插入排序
shellSort(a,n,m);
}
}
System.out.println(Arrays.toString(a));
}
/**
* 简单的插入排序算法
* @param a 需要进行插入排序的数组
* @param startIndex 插入排序的起始索引
* @param space 插入排序的步长
*/
public static void shellSort(int[] a,int startIndex,int space) {
//循环右边的无序队列 - 从左到右
for (int i=startIndex + space; i<a.length; i+=space) {
//循环插入到左边的有序队列中,并且使队列有序 - 从左到右
for (int j=i-space; j>=startIndex; j-=space) {
if (a[j+space] < a[j]) {
//移动有序交换位置
int temp = a[j+space];
a[j+space] = a[j];
a[j] = temp;
}
//break;
}
}
}
}