希爾排序(最小增量排序)

2018-07-27 21:02 更新
  1. 基本思想: 算法先將要排序的一組數(shù)按某個(gè)增量d(n/2,n為要排序數(shù)的個(gè)數(shù))分成若干組,每組中記錄的下標(biāo)相差d.對(duì)每組中全部元素進(jìn)行直 接插入排序,然后再用一個(gè)較小的增量(d/2)對(duì)它進(jìn)行分組,在每組中再進(jìn)行直接插入排序。當(dāng)增量減到1時(shí),進(jìn)行直接插入排序后,排序完成。
  2. 代碼實(shí)現(xiàn):
    
    /**
     * 打印數(shù)組內(nèi)容
     * 
     * @param a
     */
    public static void saymsg(int[] src) {
        for (int i = 0; i < src.length; i++) {
            System.out.print(src[i]);
            System.out.print("  ");
        }
        System.out.println();
    }

/**

  • 希爾排序
  • @param src */ public static void shellSort(int[] src) { double d1 = src.length; int temp = 0; int index = 1; while (true) { d1 = Math.ceil(d1 / 2); int d = (int) d1; for (int x = 0; x < d; x++) { for (int i = x + d; i < src.length; i += d) { int j = i - d; temp = src[i]; for (; j >= 0 && temp < src[j]; j -= d) { src[j + d] = src[j]; } src[j + d] = temp; } System.out.println("第" + (index++) + "次排序:"); saymsg(src); } if (d == 1) break; } saymsg(src); }

public static void main(String[] args) { int[] src = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51 }; System.out.println("原始數(shù)組排序:"); saymsg(src); shellSort(src); }




![](//atts.w3cschool.cn/attachments/image/20170727/1501145470681237.gif)
*圖片來(lái)自維基百科*
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)