java中實現希爾排序演算法

來源:互聯網
上載者:User

package Utils.Sort;

/**
 

*希爾排序,要求待排序的數組必須實現Comparable介面
 

*/
 

public class ShellSort implements SortStrategy
 

{
 

private int[] increment;

/**
 

*利用希爾排序演算法對數組obj進行排序
 

*/
 

public void sort(Comparable[] obj)
 

{
 

if (obj == null)
 

{
 

throw new NullPointerException("The argument can not be null!");
 

}
 

//初始化步長
 

initGap(obj);
 

//步長依次變化(遞減)
 

for (int i = increment.length - 1 ;i >= 0 ;i-- )
 

{
 

int step = increment[i];
 

//由步長位置開始
 

for (int j = step ;j < obj.length ;j++ )
 

{
 

Comparable tmp;
 

//如果後面的小於前面的(相隔step),則與前面的交換
 

for (int m = j ;m >= step ;m = m - step )
 

{
 

if (obj[m].compareTo(obj[m - step]) < 0)
 

{
 

tmp = obj[m - step];
 

obj[m - step] = obj[m];
 

obj[m] = tmp;
 

}

//因為之前的位置必定已經比較過,所以這裡直接退出迴圈
 

else
 

{
 

break;
 

}
 

}
 

}
 

}
 

}
 

/**
 

*根據數組的長度確定求增量的公式的最大指數,公式為pow(4, i) - 3 * pow(2, i) + 1和9 * pow(4, i) - 9 * pow
 

2, i) + 1
 

*@return int[] 兩個公式的最大指數
 

*@param length 數組的長度
 

*/
 

private int[] initExponent(int length)
 

{
 

int[] exp = new int[2];
 

exp[0] = 1;
 

exp[1] = -1;
 

int[] gap = new int[2];
 

gap[0] = gap[1] = 0;
 

//確定兩個公式的最大指數
 

while (gap[0] < length)
 

{
 

exp[0]++;
 

gap[0] = (int)(Math.pow(4, exp[0]) - 3 * Math.pow(2, exp[0]) + 1);
 

}
 

exp[0]--;
 

while (gap[1] < length)
 

{
 

exp[1]++;
 

gap[1] = (int)(9 * Math.pow(4, exp[1]) - 9 * Math.pow(2, exp[1]) + 1);
 

}
 

exp[1]--;
 

return exp;
 

}

private void initGap(Comparable[] obj)
 

{
 

//利用公式初始化增量序列
 

int exp[] = initExponent(obj.length);
 

int[] gap = new int[2];
 

increment = new int[exp[0] + exp[1]];
 

//將增量數組由大到小賦值
 

for (int i = exp[0] + exp[1] - 1 ;i >= 0 ;i-- )
 

{
 

gap[0] = (int)(Math.pow(4, exp[0]) - 3 * Math.pow(2, exp[0]) + 1);
 

gap[1] = (int)(9 * Math.pow(4, exp[1]) - 9 * Math.pow(2, exp[1]) + 1);
 

//將大的增量先放入增量數組,這裡實際上是一個歸併排序
 

//不需要考慮gap[0] == gap[1]的情況,因為不可能出現相等。
 

if (gap[0] > gap[1])
 

{
 

increment[i] = gap[0];
 

exp[0]--;
 

}
 

else
 

{
 

increment[i] = gap[1];
 

exp[1]--;
 

}
 

}
 

}
 

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.