Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Best case - finding the max element as the first (<code>O(1)</code>), worst case - it is the last element checked (<code>O(n)</code>).</p> <p>The tricky part is the average case. <br>To find the average case - we need the <a href="http://en.wikipedia.org/wiki/Expected_value" rel="noreferrer">expected</a> number of iterations!</p> <p>Since you can stop after you find the maximum, we can split the problem into two parts:</p> <ol> <li><code>[0,n-1)</code>: Since on average (assuming uniform independent distribution for each element) - the number <code>n</code> has probability 1/n to be in each place, then the expected number of iterations for this part is <code>1/n + 2*((n-1)/n)/n + 3 * ((n-1)/n)^2/n + ... + (n-1) * ((n-1)/n)^(n-2)/n</code> <sup>1</sup> <br><a href="http://www.wolframalpha.com/input/?i=sum%20j*%28%28n-1%29/n%29%5E%28j-1%29%20*%20%281/n%29%20j%20from%201%20to%20n-1%20" rel="noreferrer">The above formula yields an ugly formula which is <code>O(n)</code></a></li> <li>The last element is going to be checked if the first n-1 elements did not contain the value <code>n</code>: so you need to add to the above <code>n* ((n-1)/n)^(n-1)</code>, which is <code>O(n)</code> as well (lim to infinity is <code>1/e * n</code>).</li> </ol> <p><strong>This totals in <code>O(n)</code> average time solution.</strong></p> <hr> <p>(1): The formula for each element is <code>j*((n-1)/n)^(j-1) * (1/n)</code> because:</p> <ul> <li><code>j</code> - for the number of elements checked (number of iterations)</li> <li><code>((n-1)/n)^(j-1)</code> - Probability that there is no <code>n</code> in the previous elements</li> <li><code>(1/n)</code> - Probability this number is <code>n</code>.</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload