首页 > 编程语言 > 详细

插入排序

时间:2017-05-09 10:28:30      阅读:230      评论:0      收藏:0      [点我收藏+]

    插入排序的基本原理就是:从数组的开始循环,判断当前这个数和下一个数的大小,如果大于或者小于

                那么,就向上或向下判断是否有大于或小于当前的数

    图示:

技术分享

所以说代码如下:

  

public void InsertSort(int[] unsort){
            for (int i = 1; i < unsort.Length; i++)
            {
                if (unsort[i-1]>unsort[i])
                {
                    int temp = unsort[i];
                    int j = i;
                    while (j>0&&unsort[j-1]>temp)
                    {
                        unsort[j] = unsort[j - 1];
                        j--;
                    }
                    unsort[j] = temp;
                }
            }
}

 

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

技术分享

 

插入排序

原文:http://www.cnblogs.com/student-note/p/6829214.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!