志在指尖
用双手敲打未来

C#中插入排序

classProgram
{
staticvoidMain(string[]args)
{
int[]array=new[]{234,632,23,643,2,6,-2,423,2342,43};
Console.WriteLine(“排序前:”);
Console.WriteLine(string.Join(“,”,array));
InsertSort(array);
Console.WriteLine(“排序后:”);
Console.WriteLine(string.Join(“,”,array));
Console.ReadKey();C#中插入排序
}
///<summary>
///直接插入排序
///</summary>
///<paramname=”sources”>目标数组</param>
privatestaticvoidInsertSort(int[]sources)
{
//从索引1开始,假设sources[0]已经有序
for(inti=1,len=sources.Length-1;i<=len;i++)
{
//准备要插入的数据
intinsertValue=sources[i],
//假设要插入的索引
insertIndex=i-1;
//遍历查找插入的索引位置
while(insertIndex>=0&&insertValue<sources[insertIndex])
{
//当前数据后移一位
sources[insertIndex+1]=sources[insertIndex];
insertIndex–;
}
//不满足以上条件,说明找到位置,插入数据
sources[insertIndex+1]=insertValue;
}
}
///<summary>
///直接插入排序for实现
///</summary>
///<paramname=”sources”>目标数组</param>
privatestaticvoidInsertSort1(int[]sources)
{
for(inti=1,len=sources.Length-1;i<=len;i++)
{
for(intj=i;j>0;j–)
{
if(sources[j]>sources[j-1])//>降序,<升序
{
inttemp=sources[j];
sources[j]=sources[j-1];
sources[j-1]=temp;
}
}
}
}
}

未经允许不得转载:IT技术网站 » C#中插入排序
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载