希尔排序是插入排序的升级版,为了防止出现较小的数聚集在后面而导致移动次数非常多的情况,采用分组进行插入排序。在数据量大的情况下,效果非常明显。
动图:

代码:
public class ShellSort {
public static void main(String[] args){
int[] nums = new int[]{ 8, 9, 1, 7, 2, 3, 5, 4, 6, 0 };
int[] res = sort(nums);
for(int i=0; i<res.length; i++){
System.out.print(res[i] + " ");
}
}
public static int[] sort(int[] nums){
for(int gap=nums.length / 2; gap>0; gap /= 2){
int preIndex;
int current;
for(int i=gap;i<nums.length;i++){
preIndex = i - gap;
current = nums[i];
while (preIndex >= 0 && nums[preIndex] > current){
nums[preIndex + gap] = nums[preIndex];
preIndex = preIndex -gap;
}
nums[preIndex + gap] = current;
}
}
return nums;
}
}
850

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



