3 ms·
Is one double for loop better than two for loops?
I mean, is:
for(..){
for(..){
}
}
better than
for(..){}
for(..){}
?
May it be in terms of running time, memory, etc.
This may be a dumb question, if so, i'm sorry.
- mason240 13y agoIt's not a dumb question, this idea is covered at the beginning of every data structures class and is described as Big O Notation. The difference is the growth rate. for(..){} for(..){} will grow linearly, or O(n). Iterating over 10 items will be 20 loops, while iterating over 11 items will only be 22 loops. for(..){ for(..){ } } grows exponentially, or O(n^2) Here iterating over 10 items will be 100 loops, and increasing n by 1 (to 11) results in 121 loops. Typically it preferably to user O(n) over O(n^2). This probably explains it better than I can: http://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/ http://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notat...
- redxblood 13y agoThanks a lot! Explained really well ^^
- itg 13y agoWouldn't you need them for different purposes? A double for loop would go over a 2 dimensional array while a single for loop cannot.