算法主要代码:
public static void InsertSort(int[] list)
{
int temp;
int j;
for(int i = 1; i < list.Length; ++i)
{
if (list[i] < list[i - 1])
{
temp = list[i];
list[i] = list[i - 1];
for (j = i - 2; j >= 0 && (temp < list[j]); --j)
list[j + 1] = list[j];
list[j + 1] = temp;
}
}
}
控制台实现:
static void Main(string[] args)
{
int size = 20;
int[] list = new int[size];
string strPre="";
string strAft = "";
Random rand = new Random();
for(int i = 0; i < list.Length; i++)
{
list[i] = rand.Next(1, 99);
strPre += list[i].ToString()+",";
}
Console.WriteLine("排序前:"+strPre);
InsertSort(list);
for (int i = 0; i < list.Length; i++)
{
strAft += list[i].ToString() + ",";
}
Console.WriteLine("排序后:" + strAft);
}
通过改变size,可指定数组大小,结果如下: