cs101-notes
  • CS 101 Notes
  • Big O Notation
  • Big O Cheat Sheet
  • Sorting
    • Summary
    • Bubble Sort
    • Selection Sort
    • Insertion Sort
    • Merge Sort
    • Quick Sort
  • Abstract Data Types
    • Linked List
    • Stack
    • Queue
    • Hash Maps
    • Minimum Ordered Heap
Powered by GitBook
On this page

Was this helpful?

Big O Notation

PreviousCS 101 NotesNextSummary

Last updated 5 years ago

Was this helpful?

Big O represents the running time as a function of the size of the input (N).

We simplify to just the highest order term, and ignore constant coefficients of N.

Examples:

O(N),O(N2),O(Nlog(N)),O(1)O(N), O(N^2), O(N log(N)), O(1)O(N),O(N2),O(Nlog(N)),O(1)

Formal definition:

f(n)=O(g(n)) iff ∃ constants c and n such that ∀n>n0f(n)≤cg(n)\begin{array}{c}{f(n)=O(g(n))} \\ {\text { iff } \exists \text { constants } c \text { and } n} \\ {\text { such that } \forall n>n_{0}} \\ {f(n) \leq c g(n)}\end{array}f(n)=O(g(n)) iff ∃ constants c and n such that ∀n>n0​f(n)≤cg(n)​

Basically: f(n) worst case is g(n), so f(n) will be the same or faster than g(n).

An example:

int max(int items[], int size) { // Running time is O(N)
    int largest = items[0];
    for(inti=0; i<size; i++)
        if (items[i] > largest) 
            largest = items[i]; 
    return largest;
}
Comparison of some common running times.