C# 各种内部排序方法的实现(直接插入排序、希尔排序、冒泡排序、快速排序、直接选择排序、堆排序、归并排序、基数排序)
以下代码为我在学习数据结构时自己敲出来的,除了主函数中的代码外没有做其他的测试,如有问题希望大家指出。
数据结构学习视频为青岛大学王卓老师制作,网址:https://www.bilibili.com/video/BV1nJ411V7bd?

- SqList类的实现(各排序方法均为类内部方法)
/// <summary>
/// 顺序存储结构(0号位置为缓冲区)
/// </summary>
class SqList
{
public class RedType
{
public int key; //关键字
public string otherInfo; //其他数据项
}
private int capacity;
private RedType[] r;
private int length;
public int Length {
get => length; private set => length = value; }
public int Capacity {
get => capacity; private set => capacity = value; }
public RedType this[int index] {
get => r[index]; set => r[index] = value; }
public SqList(int capacity)
{
this.capacity = capacity;
r = new RedType[capacity + 1]; //r[0]一般作哨兵或缓冲区
for (int i = 0; i < capacity + 1; i++)
{
r[i] = new RedType();
}
length = 0;
}
public SqList() : this(20)
{
}
/// <summary>
/// 添加元素
/// </summary>
/// <param name="values"></param>
public void Add(params int[] values)
{
if (values.Length > this.capacity - this.length)
{
throw new ArgumentException("顺序表容量不足");
}
int startIndex = this.length + 1;
for (int i = 0; i < values.Length; i++)
{
r[startIndex + i].key = values[i];
length++;
}
}
/// <summary>
/// 重写ToString方法
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= this.length; i++)
{
sb.Append(r[i].key + " ");
}
return sb.ToString();
}
#region 插入排序(直接插入排序, 折半插入排序, 希尔排序)
/// <summary>
/// 直接插入排序(使用"哨兵")
/// 最坏情况下Tw(n) = O(n²)
/// 平均情况下Te(n) = O(n²)
/// 稳定
/// </summary>
public void SInsertSort()
{
for (int i = 2; i <= this.length; i++)
{
if (r[i].key > r[i - 1].key) //i前面的元素已经有序, 所以若i位置的元素大于前一个元素, 则不用移动它
{
continue;
}
r[0] = r[i]; //将i元素放到"哨兵"位置
int j;
for (j = i - 1; r[0].key < r[j].key; j<
这篇博客详细介绍了C#中实现的各种内部排序方法,包括直接插入排序、希尔排序、冒泡排序、快速排序、直接选择排序、堆排序、归并排序和基数排序。作者在学习数据结构过程中自己编写了这些代码,并提供了青岛大学王卓老师的数据结构学习视频链接。
最低0.47元/天 解锁文章
&spm=1001.2101.3001.5002&articleId=109137761&d=1&t=3&u=7a91a8f6953a412c9389b340f62ff1d8)
1079

被折叠的 条评论
为什么被折叠?



