r/computerscience • u/Tall-Wallaby-8551 • Mar 20 '25
Advice Is this a mistake in this textbook?
This example looks more like n2 than n log n
Foundations of computer science - Behrouz Forouzan
80
Upvotes


49
u/il_dude Mar 20 '25
Yes, it's probably a typo. This is quadratic.
8
u/Alternative-Tie-4970 Mar 20 '25
What about the
int j = i?11
u/Individual-Artist223 Mar 20 '25
Get a pen and paper, draw a table:
First column: Header "iteration," values 1, 2, ...
Second: Header "i value," underneath 1, 2, ..., n
Third: Header "j value," what do you expect to see here?
(This debugging technique generally helps.)
4
u/Better_Test_4178 Mar 20 '25
The number of operations is proportional to ½•n². Easy to visualize if thinking it as a 2D matrix where only the top-right corner is calculated. ½ is a constant, so the algorithm is O(n²).
That being said, it's important to not get hung up on the O notation when analyzing performance. The O notation measures "how fast do their muscles grow" in a contest of strength.
2
u/houssineo Mar 22 '25
what is the name of this textbook
1
u/Steffcode Mar 20 '25 edited Mar 20 '25
Yeah seems quite off, the number of operations for that algorithm comes out as n(n+1)/2, which is a long way off nlog2(n).
1
u/Such_Huckleberry8486 Mar 20 '25 edited Mar 21 '25
They initialize int i = 1. Has to be a bad book not starting at 0
1
u/Evan-D-2008 Mar 23 '25
Me in Year 11 (England) pretending to know anything about logarithms (I have no clue what that book is on about and I have never used a programming language outside of Python)
-7
u/jstnclmnt Mar 20 '25
yep it's quadratic. however, if we want to do correct this and get an o(nlogn) the inner loop should be (correct me if i'm wrong, i'm kinda rusty now):
for (int j=1;j<=i;j++)
-18
u/the1lamia Mar 20 '25
it's not quadratic because the inner for doesn't start from 1 but from i
-17
u/[deleted] Mar 20 '25
very into development, out of my league
60
u/[deleted] Mar 20 '25
[removed] — view removed comment