HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Average Case Analysis for finding max and min value on an array

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
casearrayanalysisaveragevalueminmaxforfindingand

Problem

Given the following algorithm, to find the maximum and minimum values of an array - don't mind the language:

MaxMin(A[1..n])
    max = A[1];
    min = A[1];
    for (i = 2; i max)
            max = A[i];
        else if (A[i] < min)
            min = A[i];
    print(max, min);


I need to do a probabilistic analysis for the average case of comparisons that will be made on its execution.

So far, my solution is:

Given an indicator random variable:
$$
X_i =
\begin{cases}
\text{1, if max $>$ $A[i]$}\\
\text{0, if max $$ $A[i]$}\\
\end{cases}
$$

I already read this (unfortunately the link to the video isn't available), but it only explains for $max$ and my analysis must be for both $max$ and $min$.

Solution

First, note that the first comparison will always compare $n-1$ times, independent of the distribution of the input. So, what you really want to know is how many times the second part of the if compares. For this, you can use a indicator random variable like this:

$$
X_i =
\begin{cases}
\text{1, if A[i] $\le$ $\max$}\\
\text{0, if A[i] $>$ $\max$}\\
\end{cases}
$$

So, just like you did, assuming an uniform distribution for $A[1..n]$, the expected probability is:

$$E[x] = \sum\limits_{i=1}^{n} Pr(X_i)$$

But we do not want $Pr(i=\max)$, we want $\overline{Pr(i=\max)}$, like we stated before. So, using your probability of the $i-th$ element to be the $max$ element:

$$Pr(i = \max) = 1/i$$

We have this complement:

$$\overline{Pr(i=\max)} = (1 - 1/i)$$

From which we can put in the expected probability:

$$E[x] = \sum\limits_{i=2}^{n} (1 - 1/i) = \sum\limits_{i=2}^{n}1 - \sum\limits_{i=2}^{n}1/i = n - 1 - (\ln|n| - 1 + \Theta(1))$$

So, to get the total quantity of comparisons, we can just sum the number of comparisons of the two parts. Note that the $\Theta(1)$ can absorb a constant values.

$$(n - 1) + n - 1 - \ln|n| + 1 + \Theta(1) = 2n - 1 - \ln|n| + \Theta(1)$$

And we get the expected total number of comparions:

$$2n - \ln|n| + \Theta(1)$$

Context

StackExchange Computer Science Q#89842, answer score: 3

Revisions (0)

No revisions yet.