(7)插入排序之五 希爾排序

來源:互聯網
上載者:User

      希爾排序(Shell’s
Sort)又稱“縮小增量排序”(Diminishing Increment Sort),它也是一種屬於插入排序類的方法,但在時間效率上較前述幾種排序方法有較大的改進。時間複雜度為O(n^3/2)。理解:先將整個待排記錄序列分割成為若干子序列,分別進行直接插入排序,待整個序列中的記錄“基本有序”時,再對全體記錄進行一次直接插入排序。

void CInsertionSort::ShellSort(void)
{
const int count = 9, length = count -1;
int L[count] = {0, 49, 38, 65, 97, 76, 13, 27, 49};
const int t = 3;
int dlta[t] = {3, 2 , 1};
for (int k = 0; k < t; ++k)
{
ShellInsert(L, length, dlta[k]);
}
//列印排序結果。
for (int i = 0; i <= length; ++ i)
{
cout << L[i] << "\t";
}
cout << endl;
}


void CInsertionSort::ShellInsert(int L[], int length, int dk)
{
for (int i = dk + 1; i <= length; ++ i)
{
if (L[i] < L[i - dk])
{
L[0] = L[i];
int j = i - dk;
while (j > 0 && L[0] < L[j])
{
L[j + dk] = L[j];
j -= dk;
}
L[j + dk] = L[0];
}
}
}

      和直接排序差不多,只不過是先三三比較,再兩兩比較,即第一輪[4]和[1]比較,[5]和[2],[6]和[3],[7]和[4],[8]和[5]。簡單來說是這樣來比較,複雜來說,這隻是第一輪的第一次比較,如果符合條件還會進行第一輪的第二次比較。即for迴圈的while子迴圈。把數值代進來用大腦跑一下就OK了。

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.