C# 算法与数据结构:从理论到实践
理解算法与数据结构是 C# 专业开发的基石。无论您是在编写基于 ASP.NET Core 的高负载 Web 应用程序,还是基于 WPF 的桌面应用程序,选择正确的数据结构和高效的算法都会直接影响代码的性能、可读性和可扩展性。在本文中,我们将通过具体的 C# 代码示例,解析关键的数据结构和算法,您可以在自己的项目中立即应用它们。
1. C# 中的栈 (Stack) 和队列 (Queue)
栈 (LIFO — 后进先出) 和 队列 (FIFO — 先进先出) 是基础的数据结构,内置于 .NET 中,广泛应用于实际任务中:从方法调用处理到任务管理。
C# 中的栈
栈常用于实现操作“撤销” (undo) 或语法分析。在 C# 中,栈由 Stack<T> 类表示。
using System;using System.Collections.Generic;
public class StackExample{ public static void Main() { Stack<string> browserHistory = new Stack<string>(); // 添加元素 (Push) browserHistory.Push("主页"); browserHistory.Push("新闻"); browserHistory.Push("关于 C# 的文章"); Console.WriteLine($"最后一个页面: {browserHistory.Peek()}"); // 关于 C# 的文章 // 移除并返回顶部元素 (Pop) string lastPage = browserHistory.Pop(); Console.WriteLine($"从以下页面返回: {lastPage}"); // 关于 C# 的文章 Console.WriteLine($"当前页面: {browserHistory.Peek()}"); // 新闻 }}C# 中的队列
队列非常适合按到达顺序处理任务(例如打印队列或消息处理)。请使用 Queue<T> 类。
using System;using System.Collections.Generic;
public class QueueExample{ public static void Main() { Queue<string> printQueue = new Queue<string>(); // 将元素添加到队列末尾 (Enqueue) printQueue.Enqueue("文档1.pdf"); printQueue.Enqueue("照片.png"); printQueue.Enqueue("报告.docx"); Console.WriteLine($"第一个打印任务: {printQueue.Peek()}"); // 文档1.pdf // 从队列开头移除元素 (Dequeue) string firstJob = printQueue.Dequeue(); Console.WriteLine($"正在打印: {firstJob}"); // 文档1.pdf Console.WriteLine($"下一个: {printQueue.Peek()}"); // 照片.png }}重要提示: .NET 中还有用于多线程场景的 ConcurrentQueue<T>,并且 Stack<T> 不支持索引访问——只能访问栈顶。
2. 数组排序:快速排序 (QuickSort)
虽然 C# 中有内置的 Array.Sort() 方法,但理解排序算法对于面试和优化是必要的。快速排序 是最有效的算法之一,平均情况下的复杂度为 O(n log n)。
using System;
public class QuickSortExample{ public static void QuickSort(int[] arr, int left, int right) { if (left < right) { int pivotIndex = Partition(arr, left, right); QuickSort(arr, left, pivotIndex - 1); QuickSort(arr, pivotIndex + 1, right); } }
private static int Partition(int[] arr, int left, int right) { int pivot = arr[right]; // 基准元素 — 最后一个 int i = left - 1;
for (int j = left; j < right; j++) { if (arr[j] < pivot) { i++;