Algorithms and Data Structures in C#: A Practical Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Algorithms and Data Structures in C#: In Practice

\n\n

Understanding algorithms and data structures is a fundamental skill for any developer. Whether you are writing a high-load service, a desktop application, or a game, efficient data management directly impacts the performance and scalability of your code. In this article, we will break down key data structures and algorithms in C# (.NET) with practical examples that you can immediately apply in your projects.

\n\n

1. Dynamic Arrays and Working with List<T>

\n\n

In C#, the basic dynamic array is the List<T> class. Unlike a classic array, it automatically expands when elements are added. Let's look at its key operations and one of the most important ones — binary search.

\n\n

Binary Search only works on sorted data. Its complexity is O(log n). The algorithm halves the search range at each step.

\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; // Element found, return index\n            else if (sortedList[mid] < target)\n                left = mid + 1; // Search in the right half\n            else\n                right = mid - 1; // Search in the left half\n        }\n        return -1; // Element not found\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 ? $"Element {target} found at index {result}" : "Element not found");\n    }\n}
\n\n

Why is this important? List<T> is used in 90% of projects. The ability to quickly search data in it is key to performance.

\n\n

2. Stack and Queue: LIFO and FIFO in Practice

\n\n

Stack and Queue are collections with a clearly defined access order. They are indispensable for processing calls, syntactic analysis, and working with tasks.

\n\n

Stack (LIFO — Last In, First Out)

\n

It is used, for example, to check the correctness of brackets in code.

\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}' — correct brackets: {IsValidBrackets(test1)}");\n        Console.WriteLine($"'{test2}' — correct brackets: {IsValidBrackets(test2)}");\n    }\n}
\n\n

Queue (FIFO — First In, First Out)

\n

Perfectly suited for processing tasks in the order they arrive (e.g., a print queue).

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

Blogs

Book Recommendations