zoukankan      html  css  js  c++  java
  • 排序算法之插入排序

     

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

    Image(6)

    /// <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();
            }

    http://www.cnblogs.com/kkun/archive/2011/11/23/2260265.html

  • 相关阅读:
    SP6779 GSS7
    P2218 [HAOI2007]覆盖问题
    day10-包的定义和内部类
    day09-final、多态、抽象类、接口
    day08-代码块和继承
    day07-变量,封装
    day05-方法、数组
    day04-switch、循环语句
    day03-运算符、键盘录入
    day02-基本概念
  • 原文地址:https://www.cnblogs.com/wuyuankun/p/4752697.html
Copyright © 2011-2022 走看看