C#算法基础之希尔排序

时间:2022-06-11 10:14:40
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsolePractice
{
class CArray
{
private int[] arr;
//数组大小
private int upper;
//下标
private int numElements; /// <summary>
/// 初始化数组参数
/// </summary>
/// <param name="size"></param>
public CArray(int size)
{
arr = new int[size];
upper = size - ;
numElements = ;
} /// <summary>
/// 插入方法
/// </summary>
/// <param name="item">存储的数</param>
public void Insert(int item)
{
arr[numElements] = item;
numElements++;
} /// <summary>
/// 输出方法
/// </summary>
public void DisplayElements()
{
for (int i = ; i <= upper; i++)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine();
} /// <summary>
/// 清除数组
/// </summary>
public void Clear()
{
for (int i = ; i <= upper; i++)
{
arr[i] = ;
}
numElements = ;
} /*
* 希尔排序其实就是插入排序的改进,可以按任意数量自增
*/
/// <summary>
/// 希尔排序算法
/// </summary>
public void ShellSort()
{
int inner, temp;
//每次按3自增
int h = ;
while (h > )
{
for (int outer = h; outer <= upper; outer++)
{
temp = arr[outer];
inner = outer;
//把一个元素取出来逐个跟之前h距离的元素比较。
//若该元素较小则较大的元素往右移。
//若该元素较大则结束循环。
while (inner > h- && arr[inner - h] >= temp)
{
arr[inner] = arr[inner - h];
inner -= h;
}
arr[inner] = temp;
this.DisplayElements();
}
//h--;
h = (h - ) % h;
Console.WriteLine("h=" + h);
}
}
} class C_shape
{
static void Main()
{
CArray nums = new CArray();
Random rnd = new Random();
for (int i = ; i < ; i++)
{
nums.Insert(rnd.Next(, ));
}
Console.WriteLine("Before sorting:");
nums.DisplayElements();
Console.WriteLine("During sorting:");
nums.ShellSort();
Console.WriteLine("After sorting:");
nums.DisplayElements();
Console.ReadKey();
}
}
}

运行结果:
C#算法基础之希尔排序