希爾排序

這裏寫圖片描述

package sort;

import java.util.ArrayList;

/*
 * 希爾排序
 * 
 * 希爾排序其實就是在插入排序基礎上,加上一個步長計算
 */

public class shellSort
{
    int gap ;//步長
    int [] array = { 9 , 4 , 1 , 3 , 5 , 6 , 8 } ;


    public void sort ()
    {
        //增量序列
        for ( gap = array.length/2 ; gap >= 1 ; gap = gap/2 )
        {
            //插入排序  第一次以步長所對應的數據爲起點
            for ( int i = gap ; i < array.length ; i ++ )
            {
                //與插入不同的是,插入是起點與起點前面數據一一比較(--) 希爾是以固定步長的數據比較,起點下標越往後比較的越多
                for ( int j = i - gap  ; j >= 0  && array [j] > array [j+gap] ; j -= gap )
                {
                    int temp = array [j] ;
                    array [j] = array [j+gap] ;
                    array [j+gap] = temp ;
                }
            }
        }
    }



    public void display ()
    {
        for ( int i = 0 ; i < array.length ; ++ i )
        {
            System.out.print ( array [i] + " " );
        }
        System.out.println (  );
    }
}
發佈了43 篇原創文章 · 獲贊 25 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章