插入排序:对于少量元素排序,它是一个有效的算法。
插入排序算法(递增)描述伪代码:
C#实现代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InsectionSort
{
class Program
{
static void Main(string[] args)
{
int key,j;
int[] a={2,4,6,8,0,1,3,5,7,9};
/*
// 递增
for (int i = 1; i < a.Length; i++)
{
key = a[i];
j = i - 1;
while (j >= 0 && a[j] > key)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
*/
// 递减
for (int i = 1; i < a.Length; i++)
{
key = a[i];
j = i - 1;
while (j >= 0 && a[j] < key)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
foreach (int data in a)
{
Console.WriteLine(data);
}
Console.ReadKey();
}
}
}