插入排序
原理:
插入排序是一种比较简单的排序算法,它将待排列的数组构造成无序和有序两部分,通过抽取无序部分的元素,作比较之后插入到有序部分的合适位置,实现有序部分的增长,无序部分的减少,直到所有元素变为有序。
过程步骤:
1.在一组数组中,第一个元素视为有序,其余为无序。
2.从第二个元素起,将数组的有序部分从后向前扫描,进行大小的比较。
3.如果待排序的元素小于有序部分的元素,则
向后移动到下一位置。
4.重复步骤2和3,直到无序部分为空,数组全部变为有序,排列完毕。
算法分析:
时间复杂度:,插入排序的最坏情况仍然是按照
次排列来完成整个数组排序的。
空间复杂度:,插入排序的额外内存的使用不随着数组规模的变化而变化。
C#代码示例:
/*
Insertion Sort
插入排序
*/
using System;
namespace Insertion_sort
{
class cInsertion
{
public void Sort(int[] value)
{
int preIndex,current;
for(int i = 1; i < value.Length; i++)
{
preIndex = i - 1;
current = value[i];
while(preIndex >= 0 && value[preIndex] > current)
{
value[preIndex + 1] = value[preIndex];
preIndex--;
}
value[preIndex + 1] = current;
}
}
}
class Insertion
{
static void Main(string[] args)
{
int[] data = new int[10]{7,2,9,1,3,8,6,10,5,4};
cInsertion ci = new cInsertion();
ci.Sort(data);
for(int i = 0; i < data.Length;i++)
{
Console.WriteLine(data[i]);
}
Console.ReadKey();
}
}
}