Shell Sort ช่วยให้แลกเปลี่ยนสิ่งของที่อยู่ห่างไกลกันในอาร์เรย์ และลดช่องว่างระหว่างกัน นี่คือลักษณะทั่วไปของการเรียงลำดับการแทรก Shell Sort เป็นที่รู้จักในฐานะที่ Donald Shell เผยแพร่ในตอนแรก
โปรแกรมที่สาธิตการเรียงลำดับเชลล์ใน 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("\nSorted 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 loop และ for loop ช่องว่างที่ใช้สำหรับการเรียงลำดับเชลล์คือ 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;
}
}