Analyzing Algorithms Part III
Analyzing Algorithms Part III
In this lesson, we will work out a generalization for the number of instructions executed for
an array of length n
12. }
If we use the above formulas and apply an array of size 5 to them, then the
cost should match with what we calculated earlier.
= 22 + 10 + 70
= 102 instructions
Summation of Series
(/learn)
We glossed over how we converted the sum of the series 0 + 1 + 2 ...(n-1) to
( 1)
n(n-1)⁄ ? However, even though we promised to steer clear of complicated
2
mathematics as much as possible, this is one of the cardinal summations that
you must know. Without a formal proof, remember that the sum of the first
k natural numbers can be represented as:
1 + 2 + 3 + 4⋯k
k ∗ (k + 1)
=
2
k ∗ (k + 1)
=
2
5 ∗ (5 + 1)
=
2
30
=
2
= 15
However, our summation sums up to n-1 and includes a zero. We can drop
the zero because adding zero to anything yields the same value. We know:
k ∗ (k + 1)
1 + 2 + 3 + 4 ⋯ (k − 2) + (k − 1) + k =
2
(/learn)
We subtract k on both sides of the equation to get:
k ∗ (k + 1)
1 + 2 + 3 + 4 ⋯ (k − 2) + (k − 1) =
2
k 2 + k − 2k
1 + 2 + 3 + 4 ⋯ (k − 2) + (k − 1) =
2
k2 − k
1 + 2 + 3 + 4 ⋯ (k − 2) + (k − 1) =
2
k ∗ (k − 1)
1 + 2 + 3 + 4 ⋯ (k − 2) + (k − 1) =
2
5 102
10 377
25 2252
75
(/learn) 19877
100 35252
250 219377
500 876252
1000 3502502
The intention of doing the dry run and accounting for each line of code
executed is to instill in the reader that the instruction count varies with the
input size. Calculating down to this detail is often not necessary and with
experience one can correctly recognize the complexity of various code
snippets. As you'll learn in the next chapters, we reason about algorithm
complexity in a ballpark sense, and calculating exact instruction counts is
almost always unnecessary.
(/learn)
← Back Next →
(/courses/big- (/courses/big-
MARK AS COMPLETED
o- o-
notation- notation-
for- for-
Analyzing Algorithms Part II
interviews- Problem Set 1
interviews-
and- and-
beyond/m27yx8vJ0Dr) beyond/gxnn6KylLor)
Ask a Question
Report
(https://discuss.educative.io/c/big-o-for-coding-interviews-and-beyond-c-h-
an Issue
afzal/basics-analyzing-algorithms-part-iii)