Solving Recurrences

Nathan Sprague

$ $

Binary Search Recurrence

Example: Recursive Binary Search

Example: Recursive Binary Search

Step 2: Backward Substitution

\(W(1) = 1\)

\(W(x) = 1 + W(x/2)\)

\(W(n)\) \(=1 + W(n/2)\)
\(=1 + 1 + W( (n/2)/2 )\)     (substitute)
\(=2 + W(n/4)\) (simplify)
\(=2 + 1 + W( (n/4)/2 )\) (substitute)
\(=3 + W(n/8)\) (simplify)
\(...\)
\(=i + W(\frac{n}{2^i})\) (generalize)

Solve for \(i\) that results in initial condition:

\(\frac{n}{2^i} = 1\)

\(n = 2^i\)

\(i = \log_2 n\)

Substitute \(\log_2 n\) for \(i\):

\(W(n) = \log_2 n + 1\)

Step 3: Check the Answer

Applying recurrence:

\(W(1) = 1\)

\(W(2) = 1 + W(1) = 1 + 1 = 2\)

\(W(4) = 1 + W(2) = 1 + 2 = 3\)

Applying solution:

\(W(1) = \log_2 1 + 1 = 0 + 1 = 1\)

\(W(2) = \log_2 2 + 1 = 1 + 1 = 2\)

\(W(4) = \log_4 4 + 1 = 2 + 1 = 3\)

Steps to Analyzing a Recursive Algorithm

Another Example:

count the comparison values[start] == values[end]

    public static boolean unique(int[] values, int start, int end) {
        if (start >= end) {
            return true;
        } else if (values[start] == values[end]) {
            return false;
        } else {
            return unique(values, start, end - 1) 
                    && unique(values, start + 1, end);
        }

    }

Part 1:

    public static boolean unique(int[] values, int start, int end) {
        if (start >= end) {
            return true;
        } else if (values[start] == values[end]) {
            return false;
        } else {
            return unique(values, start, end - 1) 
                    && unique(values, start + 1, end);
        }

    }

\(W(1) = \color{orange}{0}\)

\(W(n) = \color{red}{1} + \color{green}{2W(n-1)}\)

Part 2:

\(W(1) = 0\)

\(W(x) = 1 + 2W(x-1)\)

\(W(n)\) \(=1 + 2W(n - 1)\)
\(=1 + 2(1 + 2W((n-1)-1 )\)     (substitute)
\(=1 + 2 + 4W(n - 2)\) (simplify)
\(=1 + 2 + 4(1 + 2W((n-2) - 1 )\) (substitute)
\(=1 + 2 + 4 + 8W(n - 3)\) (simplify)
\(...\)
\(=\sum_j^{i-1}2^j + 2^iW(n-i)\) (generalize)
\(=2^i - 1 + 2^iW(n-i)\) (generalize)

Solve for \(i\) that results in initial condition:

\(n - i = 1\)

\(i = n -1\)

Substitute \(n - 1\) for \(i\):

\(W(n) = 2^{n-1} - 1 + 2^{n-1}\times 0 = 2^{n-1} - 1\)

Part 3

Applying recurrence:

\(W(1) = 0\)

\(W(2) = 1 + 2W(0) = 1 + 0 = 1\)

\(W(3) = 1 + 2W(1) = 1 + 1 = 2\)

\(W(4) = 1 + 2W(2) = 1 + 2 = 3\)

Applying solution:

\(W(1) = 2^{1-1} - 1 = 0\)

\(W(2) = 2^{2-1} - 1 = 1\)

\(W(3) = 2^{3-1} - 1 = 3\)