希尔算法,是间隔对数组抽样,从而造成多个子数组。在这多个子数组中,保证其排序正确性。java
而后对抽样间隔逐渐变小,再次保证其排序。算法
对于这些抽样出来的子数组,应该如何排序呢?这里用到插入排序。(选择排序由于须要每次遍历,因此对于部分排序的数组,比较浪费时间)shell
希尔排序的间隔选取也是有讲究的。数组
import java.util.Arrays; public class ShellSort { public static void main(String[] args) { int[] nums = {5, 12, 5, 7, 1, 4, 7, 8, 9}; shellSort(nums); System.out.println(Arrays.toString(nums)); } public static void shellSort(int[] nums){ int len = nums.length; int h = 1; while(h<len/3) h = 3*h+1; while(h>=1){ // 以h为间隔分隔成多个子数组 for (int i = h; i < len; i++) { for(int j = i; j >=h; j-=h){ if(nums[j]<nums[j-h]){ int temp = nums[j]; nums[j] = nums[j-h]; nums[j-h] = temp; } } } h = h / 3; } } }
由于希尔排序涉及到不一样的h选取,因此复杂度研究比较复杂,故暂不作分析。code