基本的排序(C#代码)
基本的排序方法,C#代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#region 选择排序
//经典排序方法
//说明排序的思路
/// <summary>
/// 双重循环,外循环遍历一遍数据,内循环控制对比次数
/// 每次内循环就可以找出当前位置上最小的一个值
/// </summary>
/// <param name="a"></param>
protected static void SelectSort(int[] a)
{
for (int i = 0; i < a.Length; i++)
{
int k = i;
for (int j = i + 1; j < a.Length; j++)
{
if (a[j] < a[k]) k = j;
}
if (i != k)
{
int temp = a[i];
a[i] = a[k];
a[k] = temp;
}
}
foreach (int x in a)
Console.WriteLine(x);
}
#endregion
#region 冒泡排序
/// <summary>
/// 何为冒泡 即每次循环都找到一个最大值,沉底冒泡
/// </summary>
/// <param name="a"></param>
protected static void BubbleSort(int[] a)
{
for (int i = 0; i < a.Length; i++)
{
for (int j = i + 1; j < a.Length; j++)
{
if (a[j]< a[i])
{
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
foreach (int x in a)
Console.WriteLine(x);
}
#endregion
#region 希尔排序
///我理解的希尔排序
/// <summary>
/// 先取一个正整数d1<n,把所有序号相隔d1的数组元素放一组,
/// 组内进行直接插入排序;然后取d2<d1,
/// 重复上述分组和排序操作;直至di=1,即所有记录放进一个组中排序为止
/// </summary>
/// <param name="a"></param>
protected static void ShellSort(int[] a)
{
int inc = a.Length;
for (inc=inc/2; inc > 0; inc = inc / 2)//控制步长因子
{
//里面的就是插入排序的算法代码
for (int i = inc; i < a.Length; i++)
{
for (int j = 0; j <= i; j=j+inc)
{
if (a[i] < a[j])
{
int k = a[i];
a[i] = a[j];
a[j] = k;
}
}
}
}
foreach (int x in a)
Console.WriteLine(x);
}
#endregion
Looking for a job working at Home about MSBI