码迷,mamicode.com
首页 > 编程语言 > 详细

经典排序算法 – 插入排序Insertion sort

时间:2017-04-17 16:02:58      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:内容   代码   var   import   位置   ges   padding   oid   wrap   

经典排序算法 – 插入排序Insertion sort  
插入排序就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到所有插入完成。 
插入排序方法分直接插入排序和折半插入排序两种。这里仅仅介绍直接插入排序,折半插入排序留到“查找”内容中进行。 
  图1演示了对4个元素进行直接插入排序的过程。共须要(a),(b),(c)三次插入。

技术分享

下面代码仅供參考,欢迎指正

技术分享
        /// <summary>
        /// 插入排序
        /// </summary>
        /// <param name="unsorted"></param>
        static void insertion_sort(int[] unsorted)
        {
            for (int i = 1; i < unsorted.Length; i++)
            {
                if (unsorted[i - 1] > unsorted[i])
                {
                    int temp = unsorted[i];
                    int j = i;
                    while (j > 0 && unsorted[j - 1] > temp)
                    {
                        unsorted[j] = unsorted[j - 1];
                        j--;
                    }
                    unsorted[j] = temp;
                }
            }
        }

        static void Main(string[] args)
        {
            int[] x = { 6, 2, 4, 1, 5, 9 };
            insertion_sort(x);
            foreach (var item in x)
            {
                if (item > 0)
                    Console.WriteLine(item + ",");
            }
            Console.ReadLine();
        }
技术分享

经典排序算法 – 插入排序Insertion sort

标签:内容   代码   var   import   位置   ges   padding   oid   wrap   

原文地址:http://www.cnblogs.com/gavanwanggw/p/6723070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!