C#写一个希尔排序并写入中文注释
时间: 2023-07-21 16:34:17 浏览: 60
以下是使用C#编写的希尔排序代码,并附有中文注释:
```csharp
using System;
class ShellSort {
static void Main(string[] args) {
int[] arr = { 8, 3, 6, 4, 2, 9, 1, 5, 7 };
Console.WriteLine("排序前:");
foreach (int i in arr) {
Console.Write(i + " ");
}
// 计算增量(步长)序列
int gap = arr.Length / 2;
while (gap > 0) {
// 对每个增量进行插入排序
for (int i = gap; i < arr.Length; i++) {
int j = i;
int temp = arr[j];
while (j >= gap && arr[j - gap] > temp) {
arr[j] = arr[j - gap];
j -= gap;
}
arr[j] = temp;
}
gap /= 2;
}
Console.WriteLine("\n排序后:");
foreach (int i in arr) {
Console.Write(i + " ");
}
}
}
```
注释说明:
- `int[] arr = { 8, 3, 6, 4, 2, 9, 1, 5, 7 };`:定义待排序的数组。
- `int gap = arr.Length / 2;`:计算初始的增量(步长),使用希尔排序的经验值,即数组长度的一半。
- `while (gap > 0) {...}`:循环计算不同增量(步长)下的排序结果,直到增量(步长)为1。
- `for (int i = gap; i < arr.Length; i++) {...}`:对每个增量进行插入排序,从第gap个元素开始,以gap为间隔进行插入排序。
- `int j = i; int temp = arr[j];`:定义插入排序中的游标j和暂存当前元素的temp。
- `while (j >= gap && arr[j - gap] > temp) {...}`:插入排序过程中,将当前元素与已排好序的元素依次比较,找到正确的插入位置。
- `arr[j] = temp;`:将暂存的元素插入到正确的位置。
- `foreach (int i in arr) { Console.Write(i + " "); }`:输出排序后的结果。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)