Java 希爾排序

來源:互聯網
上載者:User

標籤:java   希爾排序   

效率:O(n*logN)


package sort;import utils.Util;/** * 希爾排序 *  以h為間隔,進行比較。 按一定公式,先求出最大的間隔h *  當h值大時,需要移動的元素個數就少,但移動的距離長。 內部以h步長的元素做插入排序 *  當h減小時,每趟排序需要移動的元素個數增多,但此時已接近於它們排序後的最終位置,這對於插入排序更有效率 *  * @author stone * @date   2015-7-22 下午4:39:41 */public class ShellSort {public static void main(String[] args) {//int[] ary = Util.generateIntArray(10);int[] ary = {7, 1, 3, 6, 4, 5, 2, 0};Util.printArray(ary);sort(ary);Util.printArray(ary);}static void sort(int[] ary) {int h = 1;while (ary.length/3 > h) {h = 3 * h + 1;}while (h > 0) {int j, temp;for (int i = h; i < ary.length; i++) {temp = ary[i];//j = i;//while (j > h - 1 && ary[j - h] >= temp) {//ary[j] = ary[j - h];//j -= h;//}for (j = i; j > h - 1 && ary[j - h] >= temp; j -= h) {ary[j] = ary[j - h];}ary[j] = temp;//System.out.println("移動---------");//Util.printArray(ary);}h = (h - 1) / 3;}}/* * [7, 1, 3, 6, 4, 5, 2, 0] * h=4  * temp = ary[4], i = 4 *  1: [0] 比 [4]   [0]>[4]   [4]=[0]   [0] = temp *  2: temp=ary[5]  [1] 比 [5] 不變      *  3: temp=ary[6]  [2] 比 [6] 變化   [6]=[2]   [2]=temp *  4: temp=ary[7]  [3] 比 [7] 變化   [7]=[3]   [3]=temp *  現在: *  [4, 1, 2, 0, 7, 5, 3, 6]  *       *  [1, 4, 2, 0, 7, 5, 3, 6]  1  移位次數 *  [1, 2, 4, 0, 7, 5, 3, 6]  1 *  [0, 1, 2, 4, 7, 5, 3, 6]  3 *  [0, 1, 2, 4, 7, 5, 3, 6]   *  [0, 1, 2, 4, 5, 7, 3, 6]  1 *  [0, 1, 2, 3, 4, 5, 7, 6]  3 *  [0, 1, 2, 3, 4, 5, 6, 7]  1 *   *  以h為間隔, 按一定公式,先求出最大的間隔h *  while(h>0) { *  for(i=h;i<len;i++) { *  for(迴圈比較[h]和[i-h]的值,並移位) *  } *  h = 。。。 最後一輪時 h=1. 這時  i=n   i比(i-1),(i-1)再比((i-1)-1)  從後向前相鄰兩個相比 *  } */}


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java 希爾排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.