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

    对于插入排序,我们可以理解为打扑克牌时候手上的牌从小到大排序,取一个然后插入到合适位置保持顺序,从而我们可以很明显的感受到对于少量元素,这种排序算法是比较有效的。

    原理图如下:

    实现源码:

     public static void GetSortFor(int[] nums)
            {
                for (int i = 1; i < nums.Length; i++)
                {
                    int key = nums[i];
                    int pre = i;
                    for (int j = i-1; j>=0; j--)
                    {
                        if (nums[j] > key)
                        {
                            nums[pre] = nums[j];
                            pre = pre - 1;
                        }
                    }
                    nums[pre] = key; 
                }
            }
    For循环插入排序
    public static void GetSort(int[] nums)
            {
                for (int i = 1; i < nums.Length; i++)
                {
                    int key = nums[i];
                    int pre = i - 1;
                    while (pre > -1 && nums[pre] > key)
                    {
                        nums[pre + 1] = nums[pre];
                        pre = pre - 1;
                    }
                    nums[pre + 1] = key;
                } 
            }
    While循环插入排序
  • 相关阅读:
    Mysql基础
    Mysql基础2
    Windows CMD命令大全
    python 调试方法
    LDAP
    Linux 内核与模块调试
    Linux tee命令
    Linux kgdb命令
    OpenSSL基础知识
    Linux top命令
  • 原文地址:https://www.cnblogs.com/qyzBlog/p/4223474.html
Copyright © 2011-2022 走看看