C#实现插入排序算法

C#实现插入排序算法

以下是使用C#实现插入排序算法的示例代码:

复制代码
using System;

class InsertionSort
{
    static void Main(string[] args)
    {
        int[] arr = { 64, 25, 12, 22, 11 };

        Console.WriteLine("排序前:");
        PrintArray(arr);

        InsertionSortAlgorithm(arr);

        Console.WriteLine("\n排序后:");
        PrintArray(arr);
    }

    static void InsertionSortAlgorithm(int[] arr)
    {
        int n = arr.Length;
        for (int i = 1; i < n; i++)
        {
            int key = arr[i];
            int j = i - 1;
            // 将比key大的元素向右移动一位
            while (j >= 0 && arr[j] > key)
            {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;
        }
    }

    static void PrintArray(int[] arr)
    {
        foreach (int num in arr)
        {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }
}

这段代码定义了一个名为 InsertionSort 的类,其中包含了一个静态方法 InsertionSortAlgorithm 用于实现插入排序算法。在主程序中,我们创建一个整数数组,然后调用 InsertionSortAlgorithm 方法对其进行排序,并打印排序前后的数组。

相关推荐
JieE2121 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2121 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术1 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦1 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
Scout-leaf1 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6251 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
用户497863050731 天前
(一)小红的数组操作
算法·编程语言
怕浪猫1 天前
Electron 系列文章封面图
算法·架构·前端框架
Artech2 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf