Lecture 1

Running Time

Best, Average and Worst Cases

Given a list of unsorted numbers, L, and a specific number, k, Return true if k is in L, or false otherwise.

Consider the following algorithm to solve this problem:

def number_exists(L, k): for item in L: if item == k: return True return False

How Can We Analyse Algorithms?

Theoretical Analysis Steps:

  1. Express algorithm as pseudo-code
    • Example: Find maximum element of an array
Algorithm arrayMax(A, n) Input array A of n integers Output maximum element of A currentMax <- A[0] i <- 1 while i < n do if A[i] > currentMax then currentMax <- A[i] i <- i + 1 return currentMax
  1. Count primitive operations
for i in range (10) # 1 + (n + 1) let counted operations = X # n * X # count increment # n
  1. Describe algorithm as f(n)f(n)
  1. Perform asymptotic analysis
Function term
Constant 1\approx 1
Logarithmic log2n\approx log 2 n
Linear n\approx n
N-Log-N nlog2n\approx n log 2 n
Quadratic n2\approx n 2
Cubic n3\approx n 3
Exponential 2n\approx 2 n

Big O-notation

Given functions f(n)f(n) and g(n)g(n), we say that f(n)f(n) is O(g(n))O(g(n)) if there are positive constants cc and n0n_{0} such that

f(n)cg(n)    for    nn0f(n) \le c \cdot g(n) \; \; \text{for} \; \; n \ge n_{0}

Alt text

Big-O and growth rate

Some big-O rules

Rule 1: If f(n) is a polynomial of degree d, then f(n) is O(n4)O(n^{4})

Rule 2: Use the smallest possible class of functions (the “tightest” possible bound)

Rule 3: Use the simplest expression of the class

Operations:

Type name
O(1)O(1) Constant
O(logn)O(\log n) Logarithmic
O(n)O(n) Linear
O(n2)O(n^{2}) Quadratic
O(2n)O(2^{n}) Exponential
O(n!)O(n!) Factorial

Some more operations

Alt text

Big Omega notation

Given functions f(n)f(n) and g(n)g(n), we say that f(n)f(n) is Ω(g(n))\Omega (g(n)) if there are positive constants cc and n0n_{0} such that

f(n)cg(n)    for    nn0f(n) \ge c \cdot g(n) \; \; \text{for} \; \; n \ge n_{0}

Big-Theta Notation

Given functions f(n)f(n) and Θ(n)\Theta (n), we say that f(n)f(n) is Θ(g(n))\Theta (g(n)) if there are positive constants c1,c2c_{1}, c_{2} and n0n_{0} such that

c1g(n)f(n)c2g(n)    for all    nn0c_{1} \cdot g(n) \le f(n) \le c_{2}\cdot g(n) \; \; \text{for all} \; \; n \ge n_{0}