Computer >> Máy Tính >  >> Lập trình >> C#

Chương trình Shell Sort trong C #

Shell Sort cho phép trao đổi các mục cách xa nhau trong mảng và sau đó giảm khoảng cách giữa chúng. Đây là một kiểu tổng quát của Sắp xếp chèn. Shell Sort được biết đến như là do Donald Shell xuất bản lúc đầu.

Một chương trình thể hiện loại trình bao trong C # được đưa ra như sau -

Ví dụ

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("\nSorted Array is: ");
         for (i = 0; i < n; i++) {
            Console.Write(arr[i] + " ");
         }
      }
   }
}

Đầu ra

Kết quả của chương trình trên như sau.

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

Bây giờ chúng ta hãy hiểu chương trình trên.

Trong hàm main (), đầu tiên mảng ban đầu được hiển thị. Sau đó, hàm shellSort () được gọi để thực hiện sắp xếp shell trên mảng. Đoạn mã cho điều này được đưa ra như sau -

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);

Trong hàm shellSort (), mảng đã cho được sắp xếp bằng vòng lặp while và vòng lặp for. Khoảng trống được sử dụng để sắp xếp trình bao là 3. đoạn mã của anh ta cho điều này được đưa ra như sau.

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;
   }
}