package Sort;
public class ShellSort {
//希尔排序
public static int[] shellSort(int[] array){
int n = array.length;
//确定步长
int h=1;
while(3*h+1<n){
h=3*h+1;
}
int counter=1;//第几次
while(h>0){
//注意,这里的范围是h而不是n
for(int i=0;i<h;i++){
shellSortEveryH(i,h,array);
}
h=(h-1)/3;
System.out.println("这是第"+counter+"轮希尔排序h为"+h);
display(array);
counter++;
}
return array;
}
private static void display(int[] array) {
for(int i=0;i<array.length;i++){
System.out.print(array[i]+" ");
}
System.out.println();
}
private static void shellSortEveryH(int beginIndex, int h,int[] array) {
int targerIndex = beginIndex + h; //target代表当前所要插入的元素,即我们将target放到一个合适的位置
while(targerIndex<array.length){
int temp = (int) array[targerIndex];
int previousIndex = targerIndex - h;
while(previousIndex >=0 && (int)array[previousIndex] > temp){//满足这个条件的时候将temp和previous交换位置
array[previousIndex+h] = array[previousIndex];
previousIndex = previousIndex - h;
}
//经过以上的while循环,我们已经为target找到了合适的位置。
array[previousIndex+h] = temp;
targerIndex = targerIndex + h;//为下一个target元素找到合适的位置
}
}
public static void main(String[] args) {
int[] array = new int[]{456,784,49,2,37,46,123,53
,126,465,656,7689,45,23,89,46,237};
System.out.println("原始数组数据为");
display(array);
int[] result = ShellSort.shellSort(array);
System.out.println("排序好的数组");
display(result);
}
}以下是数据测试:
原始数组数据为
456 784 49 2 37 46 123 53 126 465 656 7689 45 23 89 46 237
这是第1轮希尔排序h为4
23 89 46 2 37 46 123 53 126 465 656 7689 45 456 784 49 237
这是第2轮希尔排序h为1
23 46 46 2 37 89 123 49 45 456 656 53 126 465 784 7689 237
这是第3轮希尔排序h为0
2 23 37 45 46 46 49 53 89 123 126 237 456 465 656 784 7689
排序好的数组
2 23 37 45 46 46 49 53 89 123 126 237 456 465 656 784 7689
本文详细介绍了希尔排序算法的实现过程,并通过一个具体的示例展示了排序步骤。文章中包括了如何确定步长、如何进行每一轮排序的具体操作,以及完整的Java代码实现。
937

被折叠的 条评论
为什么被折叠?



