博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
排序算法之插入排序
阅读量:4608 次
发布时间:2019-06-09

本文共 1347 字,大约阅读时间需要 4 分钟。

1.基本思路

生活中最简单的例子就是玩扑克牌了,比如第一张牌拿到的是3,第二张是2,那么就把2放在三的前面,第三张拿的6就放在3的后面,现在手上牌的顺序是:2,3,6,第四张拿的1,因为1比6小,将6后移一位,接着比较1和3的位置,后移3,比较2和1,后移2,然后将1放在最前面的位置,这就是插入排序的基本思路。

 

2.代码实现

namespace InsertSort{    class Program    {        static void Main(string[] args)        {            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);            int[] arry = { 9, 7, 12, 6, 8, 1 };            Console.WriteLine("-------------排序前--------------");            for (int i = 0; i < arry.Length; i++)            {                Console.Write(arry[i] + " ");            }            InsertSort(arry);            Console.WriteLine("\n-------------插入排序 排序后--------------");            for (int i = 0; i < arry.Length; i++)            {                Console.Write(arry[i] + " ");            }            Console.ReadKey();        }        public static  void InsertSort(int[] arry)        {            if (arry.Length == 0 || arry == null)                return;            for (int i = 1; i < arry.Length ; i++)            {                var target = arry[i];                var j = i;                while (j > 0&&arry[j - 1] > target)                {                    arry[j] = arry[j - 1];                    j--;                }                arry[j] = target;            }        }    }}

  

 

转载于:https://www.cnblogs.com/smilejeffery/p/7218380.html

你可能感兴趣的文章
细说static关键字及其应用
查看>>
ganon抓取网页示例
查看>>
C#连接oracle数据库
查看>>
php7 操作MongoDB
查看>>
寻觅Azure上的Athena和BigQuery (二):神奇的PolyBase
查看>>
file 文件的操作
查看>>
oracle 恢复备份
查看>>
MySQL数据库目录
查看>>
SyncML 同步协议 感谢 周鹏(我只是做一个备份)
查看>>
golang 环境bash 以及shell
查看>>
Android Gradle基础实践
查看>>
ITFriend站点内測公測感悟
查看>>
[BZOJ2763][JLOI2011]飞行路线
查看>>
ajax提交表单,支持文件上传
查看>>
PHP autoload自动加载机制
查看>>
树状数组
查看>>
JDBC Update操作返回值和Insert操作返回主键
查看>>
css书写规范
查看>>
Android LBS系列03 Geocoder类与地址显示
查看>>
Maven 打包
查看>>