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 方法对其进行排序,并打印排序前后的数组。

相关推荐
全栈凯哥20 分钟前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥22 分钟前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu27 分钟前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
Humbunklung43 分钟前
机器学习算法分类
算法·机器学习·分类
Ai多利1 小时前
深度学习登上Nature子刊!特征选择创新思路
人工智能·算法·计算机视觉·多模态·特征选择
Q8137574602 小时前
中阳视角下的资产配置趋势分析与算法支持
算法
yvestine2 小时前
自然语言处理——文本表示
人工智能·python·算法·自然语言处理·文本表示
钢铁男儿2 小时前
C# 表达式和运算符(表达式和字面量)
开发语言·c#
GalaxyPokemon3 小时前
LeetCode - 148. 排序链表
linux·算法·leetcode
iceslime3 小时前
旅行商问题(TSP)的 C++ 动态规划解法教学攻略
数据结构·c++·算法·算法设计与分析