wingman007

AlgorithmsDataStructures_Essential_Algorithms_in_CSharp

Oct 26th, 2025 (edited)
904
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Markdown 6.13 KB | Software | 0 0

Essential Algorithms in C# with Examples and Complexities

A compact reference of the fundamental algorithms every programming student should learn — with C# examples, short explanations, and Big-O complexity.


📘 Table of Contents

  1. Finding Minimum and Maximum
  2. Summation and Average
  3. Filtering (Selection)
  4. Linear Search
  5. Binary Search
  6. Sorting Algorithms
  7. Counting Elements / Frequency Map
  8. Reversing a Collection
  9. Recursion Basics
  10. Tree Traversal (DFS)
  11. Graph Traversal (BFS)
  12. Swapping Elements
  13. Removing Duplicates
  14. Merging Two Sorted Arrays
  15. Matrix Operations
  16. String Algorithms
  17. Sorting by Custom Criteria
  18. Aggregate / Reduce
  19. Algorithmic Thinking Summary

1. Finding Minimum and Maximum

Concept: Iterate through elements and keep track of smallest/largest value.
Complexity: O(n)

int[] numbers = { 5, 2, 9, 1, 3 };
int min = numbers[0], max = numbers[0];

foreach (int n in numbers)
{
    if (n < min) min = n;
    if (n > max) max = n;
}
Console.WriteLine($"Min = {min}, Max = {max}");

2. Summation and Average

Complexity: O(n)

int sum = numbers.Sum();
double avg = numbers.Average();

3. Filtering (Selection)

Complexity: O(n)

List<int> even = numbers.Where(x => x % 2 == 0).ToList();

4. Linear Search

Complexity: O(n)

int target = 3;
bool found = numbers.Contains(target);

5. Binary Search

Requires sorted array.
Complexity: O(log n)

int[] sorted = { 1, 2, 3, 4, 5, 6 };
int idx = Array.BinarySearch(sorted, 4);

6. Sorting Algorithms

Bubble Sort (for teaching basics)

Complexity: O(n²)

int[] arr = { 5, 3, 8, 1 };
for (int i = 0; i < arr.Length - 1; i++)
    for (int j = 0; j < arr.Length - i - 1; j++)
        if (arr[j] > arr[j + 1])
            (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);

Built-in Sort (QuickSort / Timsort Hybrid)

Complexity: O(n log n)

Array.Sort(arr);

7. Counting Elements / Frequency Map

Complexity: O(n)

string text = "hello world";
Dictionary<char, int> freq = new();
foreach (char c in text)
{
    if (c == ' ') continue;
    freq[c] = freq.ContainsKey(c) ? freq[c] + 1 : 1;
}

8. Reversing a Collection

Complexity: O(n)

int[] a = { 1, 2, 3, 4 };
Array.Reverse(a);

9. Recursion Basics

Example: Factorial
Complexity: O(n)

int Factorial(int n) => (n <= 1) ? 1 : n * Factorial(n - 1);

10. Tree Traversal (Depth-First Search)

Complexity: O(n)

class Node { public int Val; public Node? Left, Right; public Node(int v) => Val = v; }

void InOrder(Node? n)
{
    if (n == null) return;
    InOrder(n.Left);
    Console.Write($"{n.Val} ");
    InOrder(n.Right);
}

11. Graph Traversal (Breadth-First Search)

Complexity: O(V + E)

Dictionary<int, List<int>> graph = new() {
    [1] = new() { 2, 3 },
    [2] = new() { 4 },
    [3] = new() { 4 },
    [4] = new() { }
};

Queue<int> q = new();
HashSet<int> visited = new();
q.Enqueue(1);
visited.Add(1);

while (q.Count > 0)
{
    int node = q.Dequeue();
    Console.Write($"{node} ");
    foreach (int neigh in graph[node])
        if (!visited.Contains(neigh))
        {
            visited.Add(neigh);
            q.Enqueue(neigh);
        }
}

12. Swapping Elements

Complexity: O(1)

int x = 5, y = 9;
(x, y) = (y, x);

13. Removing Duplicates

Complexity: O(n)

int[] data = { 1, 2, 2, 3, 3, 4 };
var unique = data.Distinct().ToArray();

14. Merging Two Sorted Arrays

Complexity: O(n + m)

int[] a1 = { 1, 3, 5 };
int[] a2 = { 2, 4, 6 };
int[] merged = a1.Concat(a2).OrderBy(x => x).ToArray();

15. Matrix Operations

Complexity: O(n²)

int[,] matrix = { { 1, 2 }, { 3, 4 } };
int diagSum = 0;
for (int i = 0; i < 2; i++) diagSum += matrix[i, i];

16. String Algorithms

Reverse String

string s = "hello";
string rev = new string(s.Reverse().ToArray());

Palindrome Check

bool IsPalindrome(string str)
{
    str = str.ToLower();
    return str.SequenceEqual(str.Reverse());
}

17. Sorting by Custom Criteria

Complexity: O(n log n)

var people = new[] {
    new { Name = "Bob", Age = 30 },
    new { Name = "Alice", Age = 25 }
};
var sorted = people.OrderBy(p => p.Age);

18. Aggregate / Reduce

Complexity: O(n)

int product = numbers.Aggregate(1, (acc, x) => acc * x);

19. Algorithmic Thinking Summary

Algorithm Type Example Typical Complexity
Find Min/Max Linear scan O(n)
Search (Linear) Sequential O(n)
Search (Binary) Sorted array O(log n)
Sort Bubble / QuickSort O(n²) / O(n log n)
Filter Predicate O(n)
Count Frequency HashMap O(n)
Reverse Swap O(n)
Recursion Factorial O(n)
Tree Traversal DFS O(n)
Graph Traversal BFS O(V + E)
Matrix Sum Double loop O(n²)

Author: Dr. Stoyan Cheresharov
University: Plovdiv University “Paisii Hilendarski”
Course: Algorithms and Data Structures in C# (.NET)


Add Comment
Please, Sign In to add comment