/// <summary>
/// 冒泡排序
/// </summary>
static void BubbleSort()
{
int[] array = { 5, 2, 7, 4, 8, 9, 1, 3, 6 };
int count = 0;
bool flag = true;
for (int i = 0; i < array.Length; i++)
{
flag = true;
for (int j = 0; j < array.Length - 1 - i; j++)
{
if (array[j] > array[j + 1])
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
flag = false;
}
}
count++;
if (flag)
{
break;
}
}
foreach (var item in array)
{
Console.WriteLine(item);
}
}
/// <summary>
/// 选择排序
/// </summary>
static void SelectionSort()
{
int[] array = { 5, 2, 7, 4, 8, 9, 1, 3, 6 };
int minIndex = 0;
for (int i = 0; i < array.Length - 1; i++)
{
minIndex = i;
for (int j = 1 + i; j < array.Length; j++)
{
if (array[j] < array[minIndex])
{
// 保存最小元素的下标
minIndex = j;
}
}
// 此时已经找到最小元素的下标
// 将最小元素与前面的元素交换
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
foreach (var item in array)
{
Console.WriteLine(item);
}
}
/// <summary>
/// 插入排序
/// </summary>
static void InsertionSort()
{
int[] array = { 5, 2, 7, 4, 8, 9, 1, 3, 6 };
for (int i = 1; i < array.Length; i++)
{
//定义待插入的数
int insertValue = array[i];
//找到待插入数的前一个数的下标
int insertIndex = i - 1;
while (insertIndex >= 0 && array[insertIndex] > insertValue)
{
array[insertIndex + 1] = array[insertIndex];
insertIndex--;
}
array[insertIndex + 1] = insertValue;
}
foreach (var item in array)
{
Console.WriteLine(item);
}
}
/// <summary>
/// 希尔排序
/// </summary>
static void ShellSort()
{
int[] array = { 5, 2, 7, 4, 8, 9, 1, 3, 6 };
for (int gap = array.Length / 2; gap > 0; gap /= 2)
{
Console.WriteLine("组数:" + gap);
//对数组进行分组
for (int i = gap; i < array.Length; i++)
{
for (int j = i - gap; j >= 0; j -= gap)
{
if (array[j] > array[j + gap])
{
int temp = array[j];
array[j] = array[j + gap];
array[j + gap] = temp;
}
}
}
}
foreach (var item in array)
{
Console.WriteLine(item);
}
}
C# 几种常用排序方法示例
最新推荐文章于 2022-09-20 19:00:00 发布