首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 經典排序算法實作:希爾排序

     編輯:關於C#

算法原理

希爾排序是插入排序的改進版,將陣列按間距分組進行插入排序,間距逐漸縮小至 1。時間複雜度介於 O(n log n) 到 O(n²) 之間,視間距序列而定,不穩定排序。

C# 實作

using System;

public class ShellSorter
{
    public void Sort(int[] list)
    {
        int inc;
        // 計算初始間距 (Knuth 序列: 1, 4, 13, 40...)
        for (inc = 1; inc <= list.Length / 9; inc = 3 * inc + 1) ;
        
        for (; inc > 0; inc /= 3)
        {
            for (int i = inc; i < list.Length; i += inc)
            {
                int temp = list[i];
                int j = i;
                while (j >= inc && list[j - inc] > temp)
                {
                    list[j] = list[j - inc];
                    j -= inc;
                }
                list[j] = temp;
            }
        }
    }
}

// 測試
public class Program
{
    public static void Main()
    {
        int[] arr = { 1, 5, 13, 6, 10, 55, 99, 2, 87, 12, 34, 75, 33, 47 };
        new ShellSorter().Sort(arr);
        Console.WriteLine(string.Join(" ", arr));
    }
}

間距序列選擇

序列名稱公式特點
Shell 原始n/2, n/4, ..., 1簡單但效能一般
Knuth (本文使用)(3^k - 1)/2實務表現良好
Sedgewick4^k + 3·2^(k-1) + 1理論最優序列之一
Ciura經驗最佳序列1, 4, 10, 23, 57, 132, 301, 701...

結語

希爾排序是中小型資料集的優秀選擇,實作簡單且無需額外記憶體。大規模資料建議改用快速排序、合併排序或 .NET 內建 Array.Sort (Introsort)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved