用C#实现插入排序算法:
public static int[] InsertSort(int[] num)
{
for (int i = 1; i < num.Length; i++)
{
//获取索引线左边的索引值
int sortIndex = i - 1;
//获取索引线右边的第一个值
int nonNum = num[i];
//开始循环,满足以下两个条件进入循环:
//1.索引值得大于等于0,不能为复数
//2.得满足右边的第一个值大于左边的值
while (sortIndex >= 0 && nonNum < num[sortIndex])
{
//满足条件,左边的第一个向后进行移动
num[sortIndex + 1] = num[sortIndex];
//然后索引值-1,继续比较
sortIndex--;
}
//以上循环只是移动位置,最终数字还没有插入进去,循环结束之后才插入数字
num[sortIndex+1] = nonNum;
}
return num.ToArray();
}