Consider times of "inner parts"
i=1 to n [T(s1)] (where T(s1) is the inner "j" loop)
j=1 to n 1 = n
i=1 to n [T(s1)] =
i=1 to n n = n[
i=1 to n 1] = n*n
=n2
notice it is i that is changing in the summation, not n.
This is why we can bring n "out".
In general,
i=1 to n c*i = c[
i=1 to n i]
Another useful fact:
Obviously,
i=1 to n 1 = n
In general,
i=a to n 1 = n - a + 1
specifically:
i=2 to n 1 = n - 2 + 1 = n - 1
An example:
This program finds the minimum value and then returns (writes out) the rest of
the array. (this is not in Java; I am using it only to consider time
performance)
Read(Entry[1])
Mindex = 1
for i=2 to n do
Read(Entry[i])
if Entry[i] < Entry[Mindex]
then Mindex = i
for i=Mindex + 1 to n do
Write(Entry[i])
T(n) = 2 +
= 2 +2(n - 2 + 1) + (n - (Mindex + 1) + 1)
= 2 + 2n - 4 + 2 + n - Mindex = 3n - Mindex
Clearly, Mindex may be a function of n itself.
(Remember, Mindex is the index of the minimum - not the calculations to get
there)
Consider
*Worst case analysis
*Statistically average case analysis
Remember, Mindex is the index of the minimum
minimum is first index, Mindex = 1; T(n) = 3n -1
Mindex can range from 1 to n equally likely
P(any index) = 1/n
In general:
EExpectancyOfaThing =
EMindex =
=
= 1/n
= 1/n * n(n+1)/ 2 // cancel n's
= (n+1)/2
So, Statistical average
T(n) = 3n - (n+1)/2 = 6n/2 - (n+1)/2 = (5n-1)/2
O(?) for both?
Compare (in general, when we say log in this course we will mean log2 - whether we say so explicitly or not. SO
n2 n nlog2n log2n n-1 n/log2n 2log2n
(that was mean of me - look here to help with logs)
Actually we will look at these later in Chapter 3 (Tables and Figures of text there help)
Best, Worse and Average Operation Counts
Section 2.3.3
i=2 to n 2 +
i=Mindex+1 to n 1
(over things) (thing * Probabilitything)
(all x) (Mindex * P[Mindex])
Mindex = 1 to n (Mindex * P[Mindex])
Mindex= 1 to n (Mindex)
I strongly suggest using values of n that are powers of 2 to see the patterns since log2 are integers for powers of 2):