C# 算法与数据结构:实用指南与示例

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

C# 算法与数据结构:实践篇

\n\n

理解算法与数据结构是每位开发者的基础技能。无论你是在编写高负载服务、桌面应用还是游戏,高效的数据管理直接影响代码的性能和可扩展性。在本文中,我们将通过实际示例,深入讲解 C# (.NET) 中的关键数据结构与算法,你可以立即将其应用到自己的项目中。

\n\n

1. 动态数组与 List<T> 的使用

\n\n

在 C# 中,基本的动态数组是 List<T> 类。与经典数组不同,它在添加元素时会自动扩展。下面我们来看它的关键操作,以及其中最重要的一个——二分查找。

\n\n

二分查找 (Binary Search) 仅适用于已排序的数据。其时间复杂度为 O(log n)。该算法每一步都将搜索范围对半分割。

\n\n
using System;\nusing System.Collections.Generic;\n\npublic class BinarySearchExample\n{\n    public static int BinarySearch(List<int> sortedList, int target)\n    {\n        int left = 0;\n        int right = sortedList.Count - 1;\n\n        while (left <= right)\n        {\n            int mid = left + (right - left) / 2;\n\n            if (sortedList[mid] == target)\n                return mid; // 找到元素,返回索引\n            else if (sortedList[mid] < target)\n                left = mid + 1; // 在右半部分查找\n            else\n                right = mid - 1; // 在左半部分查找\n        }\n        return -1; // 未找到元素\n    }\n\n    public static void Main()\n    {\n        var numbers = new List<int> { 2, 5, 8, 12, 16, 23, 38, 45, 56, 67 };\n        int target = 23;\n        int result = BinarySearch(numbers, target);\n        Console.WriteLine(result != -1 ? $"元素 {target} 在索引 {result} 处找到" : "未找到元素");\n    }\n}
\n\n

为什么这很重要? List<T> 在 90% 的项目中都有使用。能够快速在其中查找数据是提升性能的关键。

\n\n

2. 栈与队列:LIFO 和 FIFO 的实际应用

\n\n

栈 (Stack) 和队列 (Queue) 是具有明确访问顺序的集合。它们在处理调用、语法分析和任务管理时不可或缺。

\n\n

栈 (LIFO — 后进先出)

\n

例如,用于检查代码中括号的正确性。

\n\n
using System;\nusing System.Collections.Generic;\n\npublic class StackExample\n{\n    public static bool IsValidBrackets(string input)\n    {\n        Stack<char> stack = new Stack<char>();\n        foreach (char ch in input)\n        {\n            if (ch == '(' || ch == '{' || ch == '[')\n            {\n                stack.Push(ch);\n            }\n            else if (ch == ')' || ch == '}' || ch == ']')\n            {\n                if (stack.Count == 0) return false;\n\n                char top = stack.Pop();\n                if ((ch == ')' && top != '(') ||\n                    (ch == '}' && top != '{') ||\n                    (ch == ']' && top != '['))\n                {\n                    return false;\n                }\n            }\n        }\n        return stack.Count == 0;\n    }\n\n    public static void Main()\n    {\n        string test1 = "({[]})";\n        string test2 = "({[})";\n        Console.WriteLine($"'{test1}' — 括号正确: {IsValidBrackets(test1)}");\n        Console.WriteLine($"'{test2}' — 括号正确: {IsValidBrackets(test2)}");\n    }\n}
\n\n

队列 (FIFO — 先进先出)

\n

非常适合按任务到达的顺序进行处理(例如打印队列)。

\n\n
using System;\nusing System.Collections.Generic;\n\npublic class QueueExample\n{\n    public static void Main()\n    {\n                

博客

书籍推荐