排序算法之直接插入排序

直接插入排序定义:
   每次从无序表中取出第一个元素,把它插入到有序表的合适位置,使有序表仍然有序。直接插入排序属于稳定的排序,最坏时间复杂性为O(n^2),空间复杂度为O(1)。
class Program
{
    static void Main(string[] args)
    {
        int[] array = new[] { 234, 632, 23, 643, 2, 6, -2, 423, 2342,43 };
        Console.WriteLine("排序前:");
        Console.WriteLine(string.Join(",", array));

        InsertSort(array);

        Console.WriteLine("排序后:");
        Console.WriteLine(string.Join(",", array));
        Console.ReadKey();
    }
    /// <summary>
    /// 直接插入排序
    /// </summary>
    /// <param name="sources">目标数组</param>
    private static void InsertSort(int[] sources)
    {
        // 从索引1开始,假设sources[0]已经有序
        for (int i = 1, len = sources.Length - 1; i <= len; i++)
        {
            // 准备要插入的数据
            int insertValue = sources[i],
            // 假设要插入的索引
            insertIndex = i - 1;

            // 遍历查找插入的索引位置
            while (insertIndex >= 0 && insertValue < sources[insertIndex])
            {
                // 当前数据后移一位
                sources[insertIndex + 1] = sources[insertIndex];
                insertIndex--;
            }
            
            // 不满足以上条件,说明找到位置,插入数据
            sources[insertIndex + 1] = insertValue;
        }
    }
    
    /// <summary>
    /// 直接插入排序 for实现
    /// </summary>
    /// <param name="sources">目标数组</param>
    private static void InsertSort1(int[] sources)
    {
        for (int i = 1, len = sources.Length - 1; i <= len; i++)
        {
            for (int j = i; j > 0; j--)
            {
                if (sources[j] > sources[j - 1]) // > 降序, < 升序
                {
                    int temp = sources[j];
                    sources[j] = sources[j - 1];
                    sources[j - 1] = temp;
                }
            }
        }
    }
}

 

 
 

转载于:https://www.cnblogs.com/GodX/p/4063716.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值