数据结构之希尔排序

  • 基本原理

       希尔排序也被称为“缩小增量排序”。先将待排序的数组元素分为多个子序列,使得每个子序列的元素个数相对较小,然后对每个子序列分别进行直接插入排序,待整个待排序序列“基本有序后”,最后再对所有元素进行一次直接插入排序。

  • 程序如下
public class Test{
    public static void sort(int[] a){
        int i, j, h;
        for(h=a.length/2;h>0;h/=2){
            for(i=h;i<a.length;i++){
                int temp = a[i];
                for(j=i-h;j>=0;j-=h){
                    if(temp<a[j]){
                        a[j+h] = a[j];
                    }
                    else
                        break;
                }
                a[j+h] = temp;
            }
        }
    }
    public static void main(String[] args) {
        int[] a = {7,6,4,8,9,3,2};
        sort(a);
        for(int i=0;i<a.length;i++){
            System.out.print(a[i]+" ");
        }
    }
}

      程序结果

  • 算法分析
  1. 最好时间:O(n)
  2. 平均时间:O(nlogn)
  3. 最坏时间:O(ns) 1<=s<=2
  4. 辅助存储:O(1)
  5. 稳定性:不稳定
原文地址:https://www.cnblogs.com/jiqianqian/p/6632919.html