C++
Module 31: Data Structures Using C++Advanced60 min read

Linear & Non-Linear Data Structures: Linked Lists, Trees, Graphs (BFS/DFS) & Sorting

Implement and analyze Time/Space Complexity (Big O) for Linked Lists, Stacks, Queues, Binary Search Trees, Graphs (BFS/DFS), and Merge/Quick Sort.

Key Takeaways & Core Concepts
  • Binary Trees & BST: O(h) search/insert (O(log n) when balanced like AVL / Red-Black).
  • Graphs: Adjacency List (vector<vector<int>>), BFS (shortest unweighted path via queue), DFS (cycle detection/topological sort via recursion/stack).

1. Big O Complexity & Linear Structures

Master Linked Lists (Singly, Doubly, Circular), Stacks, Queues, Circular Queues, and Deques.

1. Merge Sort Implementation in C++
1#include <iostream>
2#include <vector>
3
4void mergeSort(std::vector<int>& a, int l, int r) {
5 if (l >= r) return;
6 int m = l + (r - l) / 2;
7 mergeSort(a, l, m);
8 mergeSort(a, m + 1, r);
9 std::vector<int> tmp;
10 int i = l, j = m + 1;
11 while (i <= m && j <= r) tmp.push_back(a[i] <= a[j] ? a[i++] : a[j++]);
12 while (i <= m) tmp.push_back(a[i++]);
13 while (j <= r) tmp.push_back(a[j++]);
14 for (int k = 0; k < (int)tmp.size(); ++k) a[l + k] = tmp[k];
15}
16
17int main() {
18 std::vector<int> a = {38, 27, 43, 3, 9, 82, 10};
19 mergeSort(a, 0, (int)a.size() - 1);
20 for (int x : a) std::cout << x << " ";
21 return 0;
22}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
22 lines
Note: Stable O(n log n) divide-and-conquer Merge Sort.

2. Trees, Heaps, Hashing & Graphs

  • Binary Trees & BST: O(h) search/insert (O(log n) when balanced like AVL / Red-Black).
  • Graphs: Adjacency List (vector<vector<int>>), BFS (shortest unweighted path via queue), DFS (cycle detection/topological sort via recursion/stack).

3. Sorting Algorithms Compared

AlgorithmBestAverageWorstSpaceStable?
Merge SortO(n log n)O(n log n)O(n log n)O(n)Yes
Quick SortO(n log n)O(n log n)O(n²)O(log n)No
Heap SortO(n log n)O(n log n)O(n log n)O(1)No
Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)