C#算法之插入排序算法

算法系列:各位朋友,我们继续C#算法的学习之路。今天同样是一个简单直观的排序算法--插入排序。插入排序的原理是通过构建有序序列,对未排序序列进行扫描,找到相应位置并插入。插入排序,在数据规模较小或者部分数据已经处于有序的情况下,其效率很高。

插入排序的事件复杂度不唯一,平均值为n的平法,其中n是列表的长度。空间复杂度为1。

C#简单例程如下:

cs 复制代码
    static void Main()
    {
        int[] array = { 3, 5, 1, 4, 6, 2 };
        Console.WriteLine("原始数组:");
        foreach (int item in array)
        {
            Console.Write(item + " ");
        }
        Console.WriteLine();
        
        InsertionSort(array);
        
        Console.WriteLine("排序后的数组:");
        foreach (int item in array)
        {
            Console.Write(item + " ");
        }
    }

    static void InsertionSort(int[] array)
    {
        int n = array.Length;
        for (int i = 1; i < n; i++)
        {
            int key = array[i];
            int j = i - 1;
            
            // 将较大的元素向后移动
            while (j >= 0 && array[j] > key)
            {
                array[j + 1] = array[j];
                j--;
            }
            
            // 将key插入到正确的位置
            array[j + 1] = key;
        }
    }
相关推荐
Nazarick4 分钟前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴27 分钟前
斐波那契数列题解
算法·leetcode
郝学胜-神的一滴1 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Keven_112 小时前
算法札记:有限差分
算法
忙里偷闲学python2 小时前
GK2A 林火蔓延预报算法说明
算法
我是伪码农3 小时前
11.21程序设计
数据结构·算法
Tisfy3 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6173 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
灯澜忆梦4 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法
Shaoshing5 小时前
LeetCode100 155.最小栈
java·数据结构·算法