Shell Sort允许交换数组中相距较远的项目,然后减小它们之间的间隔。这是对插入排序的一种概括。Shell Sort最初是由Donald Shell发布的。
演示C#中shell排序的程序如下-
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循环和for循环进行排序。用于shell排序的间隔为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; } }