Big O Examples in C++

Rajeev
Big O Examples in C++
Big O notation describes how an algorithm’s running time or space usage grows as the input size 𝑛 n increases.  In C++, you can see common Big O classes like 𝑂(1), 𝑂(log 𝑛), 𝑂(𝑛), 𝑂(𝑛 log 𝑛), and 𝑂(𝑛 2 ) in simple code patterns and STL operations.  Common Big O classes with C++ examples 𝑂(1) – Constant time The runtime does not depend on input size. // Accessing an array element by index int arr[1000]; int x = arr[5]; // O(1) // Simple arithmetic / assignment int y = a + b; // O(1) bool equal = (a == b); // O(1) // Push/back on vector (amortized) std::vector<int> v; v.push_back(10); // amortized O(1) Typical 𝑂(1) patterns: single statements, no loops depending on 𝑛, direct index access, basic arithmetic. 𝑂(𝑛) – Linear time  Runtime grows proportionally with 𝑛 usually a single loop over all elements.  // Sum of first n integers (loop version) int sumOfNumbers(int n) { int sum = 0; for (int i = 1; i <= n; ++i) { // runs n times su…

Post a Comment