CPSC 221

Running Time

Today

Announcements

  • HW1 is out — due Monday Sep 21
  • Labs meet this week; Lab Intro is due Sunday
  • PEX1 (practice for Examlet 1) releases Wednesday


Where we’re going

  • Finishing how long does it take?
  • Best, worst, average
  • Asymptotics, reprised

Where we stopped

int idxFirst (vector<int> arr, int q) {
    for (int i = 0; i < arr.size(); i++)
        if (arr[i] == q)
            return i;
    return -1;
}

How long does it take?

Algorithmic analysis — running time

int idxFirst (vector<int> arr, int q) {
    for (int i = 0; i < arr.size(); i++)
        if (arr[i] == q)
            return i;
    return -1;
}

How long does it take? It depends!

What does it depend on?

Algorithmic analysis — running time

int idxFirst (vector<int> arr, int q) {
    for (int i = 0; i < arr.size(); i++)
        if (arr[i] == q)
            return i;
    return -1;
}
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
32 11 73 21 29 86 81 92 57 61 64 15 79 44 7 45

How many times does line 3 run if \(q\) is 32?   If \(q\) is 45?   If \(q\) is 100?

Best, worst, average

int idxFirst (vector<int> arr, int q) {
    for (int i = 0; i < arr.size(); i++)
        if (arr[i] == q)
            return i;
    return -1;
}

For an array of size \(n\):

  • best case
  • worst case
  • average case

Your turn

int findMin (vector<int> arr) {
    int temp = arr[0];
    for (int i = 1; i < arr.size(); i++)
        if (arr[i] < temp)
            temp = arr[i];
    return temp;
}
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 11 73 21 29 86 81 92 57 61 64 15 79 44 7 45

Best case

Worst case

Examining the details

int idxFirst (vector<int> arr, int q) {
    for (int i = 0; i < arr.size(); i++)
        if (arr[i] == q)
            return i;
    return -1;
}

How many lines are executed in the worst case?

\(T(n) =\)


Does the ___ matter?

Does the ___ matter?

Asymptotics, reprised

\(T(n) = O(f(n))\) if there are positive constants \(c\) and \(n_0\) such that

\[T(n) \le c \cdot f(n) \quad \text{for all } n \ge n_0\]

We typically use \(f(n)\) to describe …

The reminder page

growth name
\(O(1)\) constant
\(O(\log n)\) logarithmic
\(O(\log^k n)\) poly-log
\(O(n)\) linear
\(O(n \log n)\) log-linear
\(O(n^{1+c})\) superlinear \(c > 0\)
\(O(n^2)\) quadratic
\(O(n^3)\) cubic
\(O(n^k)\) polynomial “tractable”
\(O(c^n)\) exponential “intractable”

Runtime analysis guidelines

  • Single operations — constant time
  • Consecutive operations — additive
  • Conditionals — constant for the test, plus the branch taken
  • Loops — sum of the loop body times
  • Function call — the time for that function

Back to where we started

int idxFirst (vector<int> arr, int q) {
    for (int i = 0; i < arr.size(); i++)
        if (arr[i] == q)
            return i;
    return -1;
}

In the worst case, \(T(n) =\)


Which should we use to describe it?   \(o \quad O \quad \omega \quad \Omega \quad \theta \quad \Theta\)