Exercise VII

Consider the following program

public int indexOf (String str, char target) {
  for (int i = 0; i < str.length; i++) {
    if (str.charAt(i) == target) {
      return i;
    }
  }
  return NOT_FOUND; 
}

We have counted the the number of steps indexOf takes to execute and expressed it a function $T(N)$ where $N$ is the size of the input String (str).

ScenarioExact running timeAsymptotic running time
Best-case$T(N) = 4$
Worst-case$T(N) = 4N + 3$

Exercise Complete the table above. Use Big-Oh for expressing asymptotic running time.

Solution
ScenarioExact running timeAsymptotic running time
Best-case$T(N) = 4$$O(1)$
Worst-case$T(N) = 4N + 3$$O(N)$

$O(1)$ represents running time that does not depend on the input size. It does not mean it only takes one step!