using System;
namespace TestSuanfa
{
internal class Program
{
//直接插入排序
static void InsertSort(int[] array)
{
for (int i = 1; i < array.Length; i++)
{
if (array[i] >= array[i - 1])//当前元素比已排序列最后一个元素大则直接跳过
continue;
int tmp = array[i];
int j = 1;
//i-1到0位置的元素只要比array[i]大,则往后移一位
for (j = i - 1; j >= 0; j--)
{
if (array[j] > tmp)//比array[i]大,则往后移一位
{
array[j + 1] = array[j];
continue;
}
array[j + 1] = tmp;//找到合适的插入位置了
break;
}
if (j < 0)//连第一个元素都比array[i]大,则array[i]移动到第一个位置
{
array[0] = tmp;
}
}
}
static void Main(string[] args)
{
int[] array = new int[] { 28, 4, 8, 52, 44, 6, 8, 29, 46 };
InsertSort(array);
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i] + " ");//打印结果:4 6 8 8 28 29 44 46 52
}
Console.ReadKey();
}
}
}
直接插入排序
于 2024-04-18 00:39:54 首次发布