C#語言的希爾排序程式


希爾排序允許交換陣列中相距較遠的項,然後縮小它們之間的差距。這是一種插入排序的概括。希爾排序最初是由唐納德·希爾公佈的,因此得名。

下面給出了一個演示 C# 中希爾排序的程式:

示例

 實際演示

using System;
namespace ShellSortDemo {
   public class Example {
      static void shellSort(int[] arr, int n) {
         int i, j, pos, temp;
         pos = 3;
         while (pos > 0) {
            for (i = 0; i < n; i++) {
               j = i;
               temp = arr[i];
               while ((j >= pos) && (arr[j - pos] > temp)) {
                  arr[j] = arr[j - pos];
                  j = j - pos;
               }
               arr[j] = temp;
            }
            if (pos / 2 != 0)
            pos = pos / 2;
            else if (pos == 1)
            pos = 0;
            else
            pos = 1;
         }
      }
      static void Main(string[] args) {
         int[] arr = new int[] { 56, 12, 99, 32, 1, 95, 25, 5, 100, 84 };
         int n = arr.Length;
         int i;
         Console.WriteLine("Shell Sort");
         Console.Write("Initial array is: ");
         for (i = 0; i < n; i++) {
            Console.Write(arr[i] + " ");
         }
         shellSort(arr, n);
         Console.Write("
Sorted Array is: ");          for (i = 0; i < n; i++) {             Console.Write(arr[i] + " ");          }       }    } }

輸出

上述程式的輸出如下。

Shell Sort
Initial array is: 56 12 99 32 1 95 25 5 100 84
Sorted Array is: 1 5 12 25 32 56 84 95 99 100

現在讓我們來理解一下上述程式。

在 main() 函式中,首先顯示初始陣列。然後,呼叫 shellSort() 函式對陣列執行希爾排序。此部分的程式碼片段如下所示:

int[] arr = new int[] { 56, 12, 99, 32, 1, 95, 25, 5, 100, 84 };
int n = arr.Length;
int i;
Console.WriteLine("Shell Sort");
Console.Write("Initial array is: ");
for (i = 0; i < n; i++) {
   Console.Write(arr[i] + " ");
}
shellSort(arr, n);

在 shellSort() 函式中,使用 while 迴圈和 for 迴圈對給定的陣列進行排序。希爾排序使用的間隙為 3。此部分的程式碼片段如下所示。

static void shellSort(int[] arr, int n) {
   int i, j, pos, temp;
   pos = 3;
   while (pos > 0) {
      for (i = 0; i < n; i++) {
         j = i;
         temp = arr[i];
         while ((j >= pos) && (arr[j - pos] > temp)) {
            arr[j] = arr[j - pos];
            j = j - pos;
         }  
         arr[j] = temp;
      }
      if (pos / 2 != 0)
      pos = pos / 2;
      else if (pos == 1)
      pos = 0;
      else
      pos = 1;
   }
}

更新時間:2020 年 6 月 27 日

736 次瀏覽

開啟您的 職業生涯

透過完成本課程獲得認證

開始
廣告
© . All rights reserved.