1.原理讲解
插入排序原理讲解
2.代码块
/// <summary>
/// 直接插入排序算法
/// </summary>
public class InsertSortAlgorithm
{
static int index = 0;
/// <summary>
/// 插入排序
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static int[] InsertSort(int[] array)
{
for (int i = 1; i < array.Length; i++)
{
int insertVal = array[i];
int insertIndex = i - 1;
while (insertIndex >= 0 && insertVal < array[insertIndex])
{
array[insertIndex + 1] = array[insertIndex];
insertIndex--;
index++;
}
array[insertIndex + 1] = insertVal;
printArray(array);
Console.WriteLine("第" + (i) + "趟");
}
Console.Write("index:" + (index) + "次数");
return array;
}
/// <summary>
/// 打印数组
/// </summary>
/// <param name="array"></param>
public static void printArray(int[] array)
{
if (array == null || array.Length <= 0)
{
return;
}
for (int i = 0; i < array.Length; i++)
{
Console.Write("[" + array[i] + "]" + ",");
}
}
}