<p>Most people with a degree in CS will certainly know what <a href="http://www.nist.gov/dads/HTML/bigOnotation.html" rel="noreferrer">Big O stands for</a>.
It helps us to measure how well an algorithm scales. </p>

<p>But I'm curious, how do <em>you</em> calculate or approximate the complexity of your algorithms?</p>

[{'answer_id': 3280, 'author': 'Matt Mitchell', 'author_id': 364, 'author_profile': 'https://Stackoverflow.com/users/364', 'pm_score': 3, 'selected': False, 'text': '<p>Familiarity with the algorithms/data structures I use and/or quick glance analysis of iteration nesting.  The difficulty is when you call a library function, possibly multiple times - you can often be unsure of whether you are calling the function unnecessarily at times or what implementation they are using.  Maybe library functions should have a complexity/efficiency measure, whether that be Big O or some other metric, that is available in documentation or even <a href="http://en.wikipedia.org/wiki/IntelliSense" rel="noreferrer">IntelliSense</a>.</p>\n'}, {'answer_id': 3297, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 3, 'selected': False, 'text': '<p>Break down the algorithm into pieces you know the big O notation for, and combine through big O operators. That\'s the only way I know of.</p>\n\n<p>For more information, check the <a href="http://en.wikipedia.org/wiki/Big_O_notation" rel="noreferrer">Wikipedia page</a> on the subject.</p>\n'}, {'answer_id': 3368, 'author': 'DShook', 'author_id': 370, 'author_profile': 'https://Stackoverflow.com/users/370', 'pm_score': 8, 'selected': False, 'text': "<p>Big O gives the upper bound for time complexity of an algorithm.  It is usually used in conjunction with processing data sets (lists) but can be used elsewhere.  </p>\n\n<p>A few examples of how it's used in C code.</p>\n\n<p>Say we have an array of n elements</p>\n\n<pre><code>int array[n];\n</code></pre>\n\n<p>If we wanted to access the first element of the array this would be O(1) since it doesn't matter how big the array is, it always takes the same constant time to get the first item.</p>\n\n<pre><code>x = array[0];\n</code></pre>\n\n<p>If we wanted to find a number in the list:</p>\n\n<pre><code>for(int i = 0; i &lt; n; i++){\n    if(array[i] == numToFind){ return i; }\n}\n</code></pre>\n\n<p>This would be O(n) since at most we would have to look through the entire list to find our number.  The Big-O is still O(n) even though we might find our number the first try and run through the loop once because Big-O describes the upper bound for an algorithm (omega is for lower bound and theta is for tight bound).</p>\n\n<p>When we get to nested loops:</p>\n\n<pre><code>for(int i = 0; i &lt; n; i++){\n    for(int j = i; j &lt; n; j++){\n        array[j] += 2;\n    }\n}\n</code></pre>\n\n<p>This is O(n^2) since for each pass of the outer loop ( O(n) ) we have to go through the entire list again so the n's multiply leaving us with n squared.</p>\n\n<p>This is barely scratching the surface but when you get to analyzing more complex algorithms complex math involving proofs comes into play.  Hope this familiarizes you with the basics at least though.</p>\n"}, {'answer_id': 4515, 'author': 'sven', 'author_id': 46, 'author_profile': 'https://Stackoverflow.com/users/46', 'pm_score': 5, 'selected': False, 'text': '<p>Seeing the answers here I think we can conclude that most of us do indeed approximate the order of the algorithm by <em>looking</em> at it and use common sense instead of calculating it with, for example, the <a href="http://en.wikipedia.org/wiki/Master_theorem" rel="noreferrer">master method</a> as we were thought at university.\nWith that said I must add that even the professor encouraged us (later on) to actually <em>think</em> about it instead of just calculating it.</p>\n\n<p>Also I would like to add how it is done for <strong>recursive functions</strong>:</p>\n\n<p>suppose we have a function like (<a href="http://plt-scheme.org/" rel="noreferrer">scheme code</a>):</p>\n\n<pre><code>(define (fac n)\n    (if (= n 0)\n        1\n            (* n (fac (- n 1)))))\n</code></pre>\n\n<p>which recursively calculates the factorial of the given number.</p>\n\n<p>The first step is to try and determine the performance characteristic for <em>the body of the function only</em> in this case, nothing special is done in the body, just a multiplication (or the return of the value 1).</p>\n\n<p>So the <strong>performance for the body is: O(1)</strong> (constant).</p>\n\n<p>Next try and determine this for the <em>number of recursive calls</em>. In this case we have n-1 recursive calls.</p>\n\n<p>So the <strong>performance for the recursive calls is: O(n-1)</strong> (order is n, as we throw away the insignificant parts).</p>\n\n<p>Then put those two together and you then have the performance for the whole recursive function:  </p>\n\n<p><strong>1 * (n-1) = O(n)</strong></p>\n\n<hr>\n\n<p><a href="https://stackoverflow.com/users/1192/peter-holmdahl">Peter</a>, to answer <a href="https://stackoverflow.com/questions/3255/big-o-how-do-you-calculateapproximate-it#12001">your raised issues;</a> the method I describe here actually handles this quite well. But keep in mind that this is still an <em>approximation</em> and not a full mathematically correct answer. The method described here is also one of the methods we were taught at university, and if I remember correctly was used for far more advanced algorithms than the factorial I used in this example.<br>\nOf course it all depends on how well you can estimate the running time of the body of the function and the number of recursive calls, but that is just as true for the other methods.</p>\n'}, {'answer_id': 5943, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>Big O notation is useful because it's easy to work with and hides unnecessary complications and details (for some definition of unnecessary). One nice way of working out the complexity of divide and conquer algorithms is the tree method. Let's say you have a version of quicksort with the median procedure, so you split the array into perfectly balanced subarrays every time.</p>\n\n<p>Now build a tree corresponding to all the arrays you work with. At the root you have the original array, the root has two children which are the subarrays. Repeat this until you have single element arrays at the bottom. </p>\n\n<p>Since we can find the median in O(n) time and split the array in two parts in O(n) time, the work done at each node is O(k) where k is the size of the array. Each level of the tree contains (at most) the entire array so the work per level is O(n) (the sizes of the subarrays add up to n, and since we have O(k) per level we can add this up). There are only log(n) levels in the tree since each time we halve the input.</p>\n\n<p>Therefore we can upper bound the amount of work by O(n*log(n)). </p>\n\n<p>However, Big O hides some details which we sometimes can't ignore. Consider computing the Fibonacci sequence with</p>\n\n<pre><code>a=0;\nb=1;\nfor (i = 0; i &lt;n; i++) {\n    tmp = b;\n    b = a + b;\n    a = tmp;\n}\n</code></pre>\n\n<p>and lets just assume the a and b are BigIntegers in Java or something that can handle arbitrarily large numbers. Most people would say this is an O(n) algorithm without flinching. The reasoning is that you have n iterations in the for loop and O(1) work in side the loop. </p>\n\n<p>But Fibonacci numbers are large, the n-th Fibonacci number is exponential in n so just storing it will take on the order of n bytes. Performing addition with big integers will take O(n) amount of work. So the total amount of work done in this procedure is </p>\n\n<p>1 + 2 + 3 + ... + n = n(n-1)/2 = O(n^2)</p>\n\n<p>So this algorithm runs in quadradic time!</p>\n"}, {'answer_id': 11220, 'author': 'Adam', 'author_id': 1341, 'author_profile': 'https://Stackoverflow.com/users/1341', 'pm_score': 4, 'selected': False, 'text': "<p>Basically the thing that crops up 90% of the time is just analyzing loops.  Do you have single, double, triple nested loops?  The you have O(n), O(n^2), O(n^3) running time.</p>\n\n<p>Very rarely (unless you are writing a platform with an extensive base library (like for instance, the .NET BCL, or C++'s STL) you will encounter anything that is more difficult than just looking at your loops (for statements, while, goto, etc...)</p>\n"}, {'answer_id': 24582, 'author': 'OysterD', 'author_id': 2638, 'author_profile': 'https://Stackoverflow.com/users/2638', 'pm_score': 5, 'selected': False, 'text': '<p>Small reminder: the <code>big O</code> notation is used to denote <em>asymptotic</em> complexity (that is, when the size of the problem grows to infinity), <em>and</em> it hides a constant.</p>\n\n<p>This means that between an algorithm in O(n) and one in O(n<sup>2</sup>), the fastest is not always the first one (though there always exists a value of n such that for problems of size >n, the first algorithm is the fastest).</p>\n\n<p>Note that the hidden constant very much depends on the implementation!</p>\n\n<p>Also, in some cases, the runtime is not a deterministic function of the <em>size</em> n of the input. Take sorting using quick sort for example: the time needed to sort an array of n elements is not a constant but depends on the starting configuration of the array. </p>\n\n<p>There are different time complexities: </p>\n\n<ul>\n<li>Worst case (usually the simplest to figure out, though not always very meaningful)</li>\n<li><p>Average case (usually much harder to figure out...)</p></li>\n<li><p>...</p></li>\n</ul>\n\n<p>A good introduction is <em>An Introduction to the Analysis of Algorithms</em> by R. Sedgewick and P. Flajolet.</p>\n\n<p>As you say, <code>premature optimisation is the root of all evil</code>, and (if possible) <em>profiling</em> really should always be used when optimising code. It can even help you determine the complexity of your algorithms.</p>\n'}, {'answer_id': 46502, 'author': 'Eric', 'author_id': 4540, 'author_profile': 'https://Stackoverflow.com/users/4540', 'pm_score': 2, 'selected': False, 'text': '<p>In addition to using the master method (or one of its specializations), I test my algorithms experimentally.  This can\'t <em>prove</em> that any particular complexity class is achieved, but it can provide reassurance that the mathematical analysis is appropriate.  To help with this reassurance, I use code coverage tools in conjunction with my experiments, to ensure that I\'m exercising all the cases.</p>\n\n<p>As a very simple example say you wanted to do a sanity check on the speed of the .NET framework\'s list sort.  You could write something like the following, then analyze the results in Excel to make sure they did not exceed an n*log(n) curve.</p>\n\n<p>In this example I measure the number of comparisons, but it\'s also prudent to examine the actual time required for each sample size.  However then you must be even more careful that you are just measuring the algorithm and not including artifacts from your test infrastructure.</p>\n\n<pre><code>int nCmp = 0;\nSystem.Random rnd = new System.Random();\n\n// measure the time required to sort a list of n integers\nvoid DoTest(int n)\n{\n   List&lt;int&gt; lst = new List&lt;int&gt;(n);\n   for( int i=0; i&lt;n; i++ )\n      lst[i] = rnd.Next(0,1000);\n\n   // as we sort, keep track of the number of comparisons performed!\n   nCmp = 0;\n   lst.Sort( delegate( int a, int b ) { nCmp++; return (a&lt;b)?-1:((a&gt;b)?1:0)); }\n\n   System.Console.Writeline( "{0},{1}", n, nCmp );\n}\n\n\n// Perform measurement for a variety of sample sizes.\n// It would be prudent to check multiple random samples of each size, but this is OK for a quick sanity check\nfor( int n = 0; n&lt;1000; n++ )\n   DoTest(n);\n</code></pre>\n'}, {'answer_id': 46607, 'author': 'Giovanni Galbo', 'author_id': 4050, 'author_profile': 'https://Stackoverflow.com/users/4050', 'pm_score': 7, 'selected': False, 'text': '<p>While knowing how to figure out the Big O time for your particular problem is useful, knowing some general cases can go a long way in helping you make decisions in your algorithm.</p>\n\n<p>Here are some of the most common cases, lifted from <a href="http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions" rel="noreferrer">http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions</a>:</p>\n\n<p>O(1) - Determining if a number is even or odd; using a constant-size lookup table or hash table</p>\n\n<p>O(logn) - Finding an item in a sorted array with a binary search</p>\n\n<p>O(n) - Finding an item in an unsorted list; adding two n-digit numbers</p>\n\n<p>O(n<sup>2</sup>) - Multiplying two n-digit numbers by a simple algorithm; adding two n×n matrices; bubble sort or insertion sort</p>\n\n<p>O(n<sup>3</sup>) - Multiplying two n×n matrices by simple algorithm</p>\n\n<p>O(c<sup>n</sup>) - Finding the (exact) solution to the traveling salesman problem using dynamic programming; determining if two logical statements are equivalent using brute force</p>\n\n<p>O(n!) - Solving the traveling salesman problem via brute-force search</p>\n\n<p>O(n<sup>n</sup>) - Often used instead of O(n!) to derive simpler formulas for asymptotic complexity</p>\n'}, {'answer_id': 119563, 'author': 'Martin', 'author_id': 1529, 'author_profile': 'https://Stackoverflow.com/users/1529', 'pm_score': 3, 'selected': False, 'text': '<p>Less useful generally, I think, but for the sake of completeness there is also a <a href="http://en.wikipedia.org/wiki/Big_O_notation#Family_of_Bachmann.E2.80.93Landau_notations" rel="noreferrer">Big Omega Ω</a>, which defines a lower-bound on an algorithm\'s complexity, and a <a href="http://en.wikipedia.org/wiki/Big_O_notation#Related_asymptotic_notations" rel="noreferrer">Big Theta Θ</a>, which defines both an upper and lower bound.</p>\n'}, {'answer_id': 202624, 'author': 'JB King', 'author_id': 8745, 'author_profile': 'https://Stackoverflow.com/users/8745', 'pm_score': 2, 'selected': False, 'text': "<p>Don't forget to also allow for space complexities that can also be a cause for concern if one has limited memory resources.  So for example you may hear someone wanting a constant space algorithm which is basically a way of saying that the amount of space taken by the algorithm doesn't depend on any factors inside the code.</p>\n\n<p>Sometimes the complexity can come from how many times is something called, how often is a loop executed, how often is memory allocated, and so on is another part to answer this question.</p>\n\n<p>Lastly, big O can be used for worst case, best case, and amortization cases where generally it is the worst case that is used for describing how bad an algorithm may be.</p>\n"}, {'answer_id': 360825, 'author': 'John D. Cook', 'author_id': 25188, 'author_profile': 'https://Stackoverflow.com/users/25188', 'pm_score': 4, 'selected': False, 'text': "<p>If you want to estimate the order of your code empirically rather than by analyzing the code, you could stick in a series of increasing values of n and time your code.  Plot your timings on a log scale.  If the code is O(x^n), the values should fall on a line of slope n.</p>\n\n<p>This has several advantages over just studying the code.  For one thing, you can see whether you're in the range where the run time approaches its asymptotic order. Also, you may find that some code that you thought was order O(x) is really order O(x^2), for example, because of time spent in library calls.</p>\n"}, {'answer_id': 630142, 'author': 'Mike Dunlavey', 'author_id': 23771, 'author_profile': 'https://Stackoverflow.com/users/23771', 'pm_score': 5, 'selected': False, 'text': "<p>I think about it in terms of information. Any problem consists of learning a certain number of bits.</p>\n\n<p>Your basic tool is the concept of decision points and their entropy. The entropy of a decision point is the average information it will give you. For example, if a program contains a decision point with two branches, it's entropy is the sum of the probability of each branch times the log<sub>2</sub> of the inverse probability of that branch. That's how much you learn by executing that decision.</p>\n\n<p>For example, an <code>if</code> statement having two branches, both equally likely, has an entropy of 1/2 * log(2/1) + 1/2 * log(2/1) = 1/2 * 1 + 1/2 * 1 = 1. So its entropy is 1 bit.</p>\n\n<p>Suppose you are searching a table of N items, like N=1024. That is a 10-bit problem because log(1024) = 10 bits. So if you can search it with IF statements that have equally likely outcomes, it should take 10 decisions.</p>\n\n<p>That's what you get with binary search.</p>\n\n<p>Suppose you are doing linear search. You look at the first element and ask if it's the one you want. The probabilities are 1/1024 that it is, and 1023/1024 that it isn't. The entropy of that decision is 1/1024*log(1024/1) + 1023/1024 * log(1024/1023) = 1/1024 * 10 + 1023/1024 * about 0 = about .01 bit. You've learned very little! The second decision isn't much better. That is why linear search is so slow. In fact it's exponential in the number of bits you need to learn.</p>\n\n<p>Suppose you are doing indexing. Suppose the table is pre-sorted into a lot of bins, and you use some of all of the bits in the key to index directly to the table entry. If there are 1024 bins, the entropy is 1/1024 * log(1024) + 1/1024 * log(1024) + ... for all 1024 possible outcomes. This is 1/1024 * 10 times 1024 outcomes, or 10 bits of entropy for that one indexing operation. That is why indexing search is fast.</p>\n\n<p>Now think about sorting.  You have N items, and you have a list. For each item, you have to search for where the item goes in the list, and then add it to the list. So sorting takes roughly N times the number of steps of the underlying search.</p>\n\n<p>So sorts based on binary decisions having roughly equally likely outcomes all take about O(N log N) steps. An O(N) sort algorithm is possible if it is based on indexing search.</p>\n\n<p>I've found that nearly all algorithmic performance issues can be looked at in this way.</p>\n"}, {'answer_id': 630478, 'author': 'Baltimark', 'author_id': 1179, 'author_profile': 'https://Stackoverflow.com/users/1179', 'pm_score': 2, 'selected': False, 'text': '<p>What often gets overlooked is the <em>expected</em> behavior of your algorithms. <strong>It doesn\'t change the Big-O of your algorithm</strong>, but it does relate to the statement "premature optimization. . .."</p>\n\n<p>Expected behavior of your algorithm is -- very dumbed down -- how fast you can expect your algorithm to work on data you\'re most likely to see. </p>\n\n<p>For instance, if you\'re searching for a value in a list, it\'s O(n), but if you know that most lists you see have your value up front, typical behavior of your algorithm is faster. </p>\n\n<p>To really nail it down, you need to be able to describe the probability distribution of your "input space" (if you need to sort a list, how often is that list already going to be sorted? how often is it totally reversed? how often is it mostly sorted?) It\'s not always feasible that you know that, but sometimes you do. </p>\n'}, {'answer_id': 630667, 'author': 'Suma', 'author_id': 16673, 'author_profile': 'https://Stackoverflow.com/users/16673', 'pm_score': 3, 'selected': False, 'text': '<p>As to "how do you calculate" Big O, this is part of <a href="http://en.wikipedia.org/wiki/Computational_complexity_theory" rel="noreferrer">Computational complexity theory</a>. For some (many) special cases you may be able to come with some simple heuristics (like multiplying loop counts for nested loops), esp. when all you want is any upper bound estimation, and you do not mind if it is too pessimistic - which I guess is probably what your question is about.</p>\n\n<p>If you really want to answer your question for any algorithm the best you can do is to apply the theory. Besides of simplistic "worst case" analysis I have found <a href="http://en.wikipedia.org/wiki/Amortized_analysis" rel="noreferrer">Amortized analysis</a> very useful in practice.</p>\n'}, {'answer_id': 4851387, 'author': 'Marcelo Cantos', 'author_id': 9990, 'author_profile': 'https://Stackoverflow.com/users/9990', 'pm_score': 5, 'selected': False, 'text': "<p>If your cost is a polynomial, just keep the highest-order term, without its multiplier. E.g.:</p>\n\n<blockquote>\n  <p>O((n/2 + 1)*(n/2)) = O(n<sup>2</sup>/4 + n/2) = O(n<sup>2</sup>/4) = O(n<sup>2</sup>)</p>\n</blockquote>\n\n<p>This doesn't work for infinite series, mind you. There is no single recipe for the general case, though for some common cases, the following inequalities apply:</p>\n\n<blockquote>\n  <p>O(log <em>N</em>) &lt; O(<em>N</em>) &lt; O(<em>N</em> log <em>N</em>) &lt; O(<em>N</em><sup>2</sup>) &lt; O(<em>N</em><sup>k</sup>) &lt; O(e<sup><em>n</em></sup>) &lt; O(<em>n</em>!)</p>\n</blockquote>\n"}, {'answer_id': 4852098, 'author': 'Emmanuel', 'author_id': 579731, 'author_profile': 'https://Stackoverflow.com/users/579731', 'pm_score': 3, 'selected': False, 'text': '<p>For the 1st case, the inner loop is executed <code>n-i</code> times, so the total number of executions is the sum for <code>i</code> going from <code>0</code> to <code>n-1</code> (because lower than, not lower than or equal) of the <code>n-i</code>. You get finally <code>n*(n + 1) / 2</code>, so <code>O(n²/2) = O(n²)</code>.</p>\n\n<p>For the 2nd loop, <code>i</code> is between <code>0</code> and <code>n</code> included for the outer loop; then the inner loop is executed when <code>j</code> is strictly greater than <code>n</code>, which is then impossible.</p>\n'}, {'answer_id': 4852666, 'author': 'vz0', 'author_id': 209629, 'author_profile': 'https://Stackoverflow.com/users/209629', 'pm_score': 12, 'selected': True, 'text': '<p>I\'ll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the <a href="https://rads.stackoverflow.com/amzn/click/com/0321370139" rel="noreferrer" rel="nofollow noreferrer">Data Structures and Algorithms in Java</a> book.</p>\n\n<hr>\n\n<p>There is no <a href="http://en.wikipedia.org/wiki/Halting_problem" rel="noreferrer">mechanical procedure</a> that can be used to get the BigOh.</p>\n\n<p>As a "cookbook", to obtain the <a href="http://en.wikipedia.org/wiki/Big_Oh_notation" rel="noreferrer">BigOh</a> from a piece of code you first need to realize that you are creating a math formula to count how many steps of computations get executed given an input of some size.</p>\n\n<p>The purpose is simple: to compare algorithms from a theoretical point of view, without the need to execute the code. The lesser the number of steps, the faster the algorithm.</p>\n\n<p>For example, let\'s say you have this piece of code:</p>\n\n<pre><code>int sum(int* data, int N) {\n    int result = 0;               // 1\n\n    for (int i = 0; i &lt; N; i++) { // 2\n        result += data[i];        // 3\n    }\n\n    return result;                // 4\n}\n</code></pre>\n\n<p>This function returns the sum of all the elements of the array, and we want to create a formula to count the <a href="http://en.wikipedia.org/wiki/Computational_complexity_theory" rel="noreferrer">computational complexity</a> of that function:</p>\n\n<pre><code>Number_Of_Steps = f(N)\n</code></pre>\n\n<p>So we have <code>f(N)</code>, a function to count the number of computational steps. The input of the function is the size of the structure to process. It means that this function is called such as:</p>\n\n<pre><code>Number_Of_Steps = f(data.length)\n</code></pre>\n\n<p>The parameter <code>N</code> takes the <code>data.length</code> value. Now we need the actual definition of the function <code>f()</code>. This is done from the source code, in which each interesting line is numbered from 1 to 4.</p>\n\n<p>There are many ways to calculate the BigOh. From this point forward we are going to assume that every sentence that doesn\'t depend on the size of the input data takes a constant <code>C</code> number computational steps.</p>\n\n<p>We are going to add the individual number of steps of the function, and neither the local variable declaration nor the return statement depends on the size of the <code>data</code> array.</p>\n\n<p>That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this:</p>\n\n<pre><code>f(N) = C + ??? + C\n</code></pre>\n\n<p>The next part is to define the value of the <code>for</code> statement. Remember that we are counting the number of computational steps, meaning that the body of the <code>for</code> statement gets executed <code>N</code> times. That\'s the same as adding <code>C</code>, <code>N</code> times:</p>\n\n<pre><code>f(N) = C + (C + C + ... + C) + C = C + N * C + C\n</code></pre>\n\n<p>There is no mechanical rule to count how many times the body of the <code>for</code> gets executed, you need to count it by looking at what does the code do. To simplify the calculations, we are ignoring the variable initialization, condition and increment parts of the <code>for</code> statement.</p>\n\n<p>To get the actual BigOh we need the <a href="http://en.wikipedia.org/wiki/Asymptotic_analysis" rel="noreferrer">Asymptotic analysis</a> of the function. This is roughly done like this:</p>\n\n<ol>\n<li>Take away all the constants <code>C</code>.</li>\n<li>From <code>f()</code> get the <a href="http://en.wikipedia.org/wiki/Polynomial" rel="noreferrer">polynomium</a> in its <code>standard form</code>.</li>\n<li>Divide the terms of the polynomium and sort them by the rate of growth.</li>\n<li>Keep the one that grows bigger when <code>N</code> approaches <code>infinity</code>.</li>\n</ol>\n\n<p>Our <code>f()</code> has two terms:</p>\n\n<pre><code>f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1\n</code></pre>\n\n<p>Taking away all the <code>C</code> constants and redundant parts:</p>\n\n<pre><code>f(N) = 1 + N ^ 1\n</code></pre>\n\n<p>Since the last term is the one which grows bigger when <code>f()</code> approaches infinity (think on <a href="http://en.wikipedia.org/wiki/Limit_%28mathematics%29" rel="noreferrer">limits</a>) this is the BigOh argument, and the <code>sum()</code> function has a BigOh of:</p>\n\n<pre><code>O(N)\n</code></pre>\n\n<hr>\n\n<p>There are a few tricks to solve some tricky ones: use <a href="http://en.wikipedia.org/wiki/Summation" rel="noreferrer">summations</a> whenever you can.</p>\n\n<p>As an example, this code can be easily solved using summations:</p>\n\n<pre><code>for (i = 0; i &lt; 2*n; i += 2) {  // 1\n    for (j=n; j &gt; i; j--) {     // 2\n        foo();                  // 3\n    }\n}\n</code></pre>\n\n<p>The first thing you needed to be asked is the order of execution of <code>foo()</code>. While the usual is to be <code>O(1)</code>, you need to ask your professors about it. <code>O(1)</code> means (almost, mostly) constant <code>C</code>, independent of the size <code>N</code>.</p>\n\n<p>The <code>for</code> statement on the sentence number one is tricky. While the index ends at <code>2 * N</code>, the increment is done by two. That means that the first <code>for</code> gets executed only <code>N</code> steps, and we need to divide the count by two.</p>\n\n<pre><code>f(N) = Summation(i from 1 to 2 * N / 2)( ... ) = \n     = Summation(i from 1 to N)( ... )\n</code></pre>\n\n<p>The sentence number <em>two</em> is even trickier since it depends on the value of <code>i</code>. Take a look: the index i takes the values: 0, 2, 4, 6, 8, ..., 2 * N, and the second <code>for</code> get executed: N times the first one, N - 2 the second, N - 4 the third... up to the N / 2 stage, on which the second <code>for</code> never gets executed.</p>\n\n<p>On formula, that means:</p>\n\n<pre><code>f(N) = Summation(i from 1 to N)( Summation(j = ???)(  ) )\n</code></pre>\n\n<p>Again, we are counting <strong>the number of steps</strong>. And by definition, every summation should always start at one, and end at a number bigger-or-equal than one.</p>\n\n<pre><code>f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) )\n</code></pre>\n\n<p>(We are assuming that <code>foo()</code> is <code>O(1)</code> and takes <code>C</code> steps.)</p>\n\n<p>We have a problem here: when <code>i</code> takes the value <code>N / 2 + 1</code> upwards, the inner Summation ends at a negative number! That\'s impossible and wrong. We need to split the summation in two, being the pivotal point the moment <code>i</code> takes <code>N / 2 + 1</code>.</p>\n\n<pre><code>f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C )\n</code></pre>\n\n<p>Since the pivotal moment <code>i &gt; N / 2</code>, the inner <code>for</code> won\'t get executed, and we are assuming a constant C execution complexity on its body.</p>\n\n<p>Now the summations can be simplified using some identity rules:</p>\n\n<ol>\n<li>Summation(w from 1 to N)( C ) = N * C</li>\n<li>Summation(w from 1 to N)( A (+/-) B ) = Summation(w from 1 to N)( A ) (+/-) Summation(w from 1 to N)( B )</li>\n<li>Summation(w from 1 to N)( w * C ) = C * Summation(w from 1 to N)( w ) (C is a constant, independent of <code>w</code>)</li>\n<li>Summation(w from 1 to N)( w ) = (N * (N + 1)) / 2</li>\n</ol>\n\n<p>Applying some algebra:</p>\n\n<pre><code>f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C )\n\nf(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C )\n\nf(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C )\n\n=&gt; Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i )\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C )\n\n=&gt; (N / 2 - 1) * (N / 2 - 1 + 1) / 2 = \n\n   (N / 2 - 1) * (N / 2) / 2 = \n\n   ((N ^ 2 / 4) - (N / 2)) / 2 = \n\n   (N ^ 2 / 8) - (N / 4)\n\nf(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C )\n\nf(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C )\n\nf(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2)\n\nf(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2)\n\nf(N) = C * ( N ^ 2 / 4 ) + C * N\n\nf(N) = C * 1/4 * N ^ 2 + C * N\n</code></pre>\n\n<p>And the BigOh is:</p>\n\n<pre><code>O(N²)\n</code></pre>\n'}, {'answer_id': 4855527, 'author': 'laynece', 'author_id': 534263, 'author_profile': 'https://Stackoverflow.com/users/534263', 'pm_score': 2, 'selected': False, 'text': "<p>For code A, the outer loop will execute for <code>n+1</code> times, the '1' time means the process which checks the whether i still meets the requirement. And inner loop runs <code>n</code> times, <code>n-2</code> times.... Thus,<code>0+2+..+(n-2)+n= (0+n)(n+1)/2= O(n²)</code>.</p>\n\n<p>For code B, though inner loop wouldn't step in and execute the foo(), the inner loop will be executed for n times depend on outer loop execution time, which is O(n)</p>\n"}, {'answer_id': 16492899, 'author': 'Gavriel Feria', 'author_id': 1928927, 'author_profile': 'https://Stackoverflow.com/users/1928927', 'pm_score': 2, 'selected': False, 'text': "<p>I don't know how to programmatically solve this, but the first thing people do is that we sample the algorithm for certain patterns in the number of operations done, say 4n^2 + 2n + 1 we have 2 rules:</p>\n\n<ol>\n<li>If we have a sum of terms, the term with the largest growth rate is kept, with other terms omitted.\n<br></li>\n<li>If we have a product of several factors constant factors are omitted.</li>\n</ol>\n\n<p> If we simplify f(x), where f(x) is the formula for number of operations done, (4n^2 + 2n + 1 explained above), we obtain the big-O value [O(n^2) in this case]. But this would have to account for Lagrange interpolation in the program, which may be hard to implement. And what if the real big-O value was O(2^n), and we might have something like O(x^n), so this algorithm probably wouldn't be programmable. But if someone proves me wrong, give me the code . . . .</p>\n"}, {'answer_id': 21512377, 'author': 'ajknzhol', 'author_id': 1112163, 'author_profile': 'https://Stackoverflow.com/users/1112163', 'pm_score': 5, 'selected': False, 'text': '<p>Lets start from the beginning.</p>\n\n<p>First of all, accept the principle that certain simple operations on data can be done in <code>O(1)</code> time, that is, in time that is independent of the size of the input. These primitive operations in C consist of</p>\n\n<ol>\n<li>Arithmetic operations (e.g. + or %).</li>\n<li>Logical operations (e.g., &amp;&amp;).</li>\n<li>Comparison operations (e.g., &lt;=).</li>\n<li>Structure accessing operations (e.g. array-indexing like A[i], or pointer fol-\nlowing with the -> operator).</li>\n<li>Simple assignment such as copying a value into a variable.</li>\n<li>Calls to library functions (e.g., scanf, printf).</li>\n</ol>\n\n<p>The justification for this principle requires a detailed study of the machine instructions (primitive steps) of a typical computer. Each of the described operations can be done with some small number of machine instructions; often only one or two instructions are needed.\nAs a consequence, several kinds of statements in C can be executed in <code>O(1)</code> time, that is, in some constant amount of time independent of input. These simple include</p>\n\n<ol>\n<li>Assignment statements that do not involve function calls in their expressions.</li>\n<li>Read statements.</li>\n<li>Write statements that do not require function calls to evaluate arguments.</li>\n<li>The jump statements break, continue, goto, and return expression, where\nexpression does not contain a function call.</li>\n</ol>\n\n<p>In C, many for-loops are formed by initializing an index variable to some value and\nincrementing that variable by 1 each time around the loop. The for-loop ends when\nthe index reaches some limit. For instance, the for-loop </p>\n\n<pre><code>for (i = 0; i &lt; n-1; i++) \n{\n    small = i;\n    for (j = i+1; j &lt; n; j++)\n        if (A[j] &lt; A[small])\n            small = j;\n    temp = A[small];\n    A[small] = A[i];\n    A[i] = temp;\n}\n</code></pre>\n\n<p>uses index variable i. It increments i by 1 each time around the loop, and the iterations\nstop when i reaches n − 1.</p>\n\n<p>However, for the moment, focus on the simple form of for-loop, where the <strong>difference between the final and initial values, divided by the amount by which the index variable is incremented tells us how many times we go around the loop</strong>. That count is exact, unless there are ways to exit the loop via a jump statement; it is an upper bound on the number of iterations in any case. </p>\n\n<p>For instance, the for-loop iterates <code>((n − 1) − 0)/1 = n − 1 times</code>,\nsince 0 is the initial value of i, n − 1 is the highest value reached by i (i.e., when i\nreaches n−1, the loop stops and no iteration occurs with i = n−1), and 1 is added\nto i at each iteration of the loop.</p>\n\n<p>In the simplest case, where the time spent in the loop body is the same for each\niteration, <strong>we can multiply the big-oh upper bound for the body by the number of\ntimes around the loop</strong>. Strictly speaking, we must then <strong>add O(1) time to initialize\nthe loop index and O(1) time for the first comparison of the loop index with the\nlimit</strong>, because we test one more time than we go around the loop. However, unless\nit is possible to execute the loop zero times, the time to initialize the loop and test\nthe limit once is a low-order term that can be dropped by the summation rule.</p>\n\n<hr>\n\n<p>Now consider this example:</p>\n\n<pre><code>(1) for (j = 0; j &lt; n; j++)\n(2)   A[i][j] = 0;\n</code></pre>\n\n<p>We know that <strong>line (1)</strong> takes <code>O(1)</code> time. Clearly, we go around the loop n times, as\nwe can determine by subtracting the lower limit from the upper limit found on line\n(1) and then adding 1. Since the body, line (2), takes O(1) time, we can neglect the\ntime to increment j and the time to compare j with n, both of which are also O(1).\nThus, the running time of lines (1) and (2) is the <strong>product of n and O(1)</strong>, which is <code>O(n)</code>.</p>\n\n<p>Similarly, we can bound the running time of the outer loop consisting of lines\n(2) through (4), which is</p>\n\n<pre><code>(2) for (i = 0; i &lt; n; i++)\n(3)     for (j = 0; j &lt; n; j++)\n(4)         A[i][j] = 0;\n</code></pre>\n\n<p>We have already established that the loop of lines (3) and (4) takes O(n) time.\nThus, we can neglect the O(1) time to increment i and to test whether i &lt; n in\neach iteration, concluding that each iteration of the outer loop takes O(n) time.</p>\n\n<p>The initialization i = 0 of the outer loop and the (n + 1)st test of the condition\ni &lt; n likewise take O(1) time and can be neglected. Finally, we observe that we go\naround the outer loop n times, taking O(n) time for each iteration, giving a total\n<code>O(n^2)</code> running time.</p>\n\n<hr>\n\n<p>A more practical example.</p>\n\n<p><img src="https://i.stack.imgur.com/ceoAc.png" alt="enter image description here"></p>\n'}, {'answer_id': 39050630, 'author': 'Samie Bencherif', 'author_id': 1727470, 'author_profile': 'https://Stackoverflow.com/users/1727470', 'pm_score': 2, 'selected': False, 'text': '<p>great question!</p>\n\n<p><strong>Disclaimer: this answer contains false statements see the comments below.</strong></p>\n\n<p>If you\'re using the Big O, you\'re talking about the worse case (more on what that means later). Additionally, there is capital theta for average case and a big omega for best case.</p>\n\n<p>Check out this site for a lovely formal definition of Big O: <a href="https://xlinux.nist.gov/dads/HTML/bigOnotation.html" rel="nofollow noreferrer">https://xlinux.nist.gov/dads/HTML/bigOnotation.html</a></p>\n\n<blockquote>\n  <p>f(n) = O(g(n)) means there are positive constants c and k, such that 0 ≤ f(n) ≤ cg(n) for all n ≥ k. The values of c and k must be fixed for the function f and must not depend on n. </p>\n</blockquote>\n\n<hr>\n\n<p>Ok, so now what do we mean by "best-case" and "worst-case" complexities?</p>\n\n<p>This is probably most clearly illustrated through examples. For example if we are using linear search to find a number in a sorted array then the <strong>worst case</strong> is when we decide to <strong>search for the last element</strong> of the array as this would take as many steps as there are items in the array. The <strong>best case</strong> would be when we search for the <strong>first element</strong> since we would be done after the first check.</p>\n\n<p>The point of all these <em>adjective</em>-case complexities is that we\'re looking for a way to graph the amount of time a hypothetical program runs to completion in terms of the size of particular variables. However for many algorithms you can argue that there is not a single time for a particular size of input. Notice that this contradicts with the fundamental requirement of a function, any input should have no more than one output. So we come up with <em>multiple</em> functions to describe an algorithm\'s complexity. Now, even though searching an array of size n may take varying amounts of time depending on what you\'re looking for in the array and depending proportionally to n, we can create an informative description of the algorithm using best-case, average-case, and worst-case classes.</p>\n\n<p>Sorry this is so poorly written and lacks much technical information. But hopefully it\'ll make time complexity classes easier to think about. Once you become comfortable with these it becomes a simple matter of parsing through your program and looking for things like for-loops that depend on array sizes and reasoning based on your data structures what kind of input would result in trivial cases and what input would result in worst-cases.</p>\n'}, {'answer_id': 54784424, 'author': 'HmT', 'author_id': 8633895, 'author_profile': 'https://Stackoverflow.com/users/8633895', 'pm_score': 3, 'selected': False, 'text': '<p>I would like to explain the Big-O in a little bit different aspect.</p>\n\n<p>Big-O is just to compare the complexity of the programs which means how fast are they growing when the inputs are increasing and not the exact time which is spend to do the action.</p>\n\n<p>IMHO in the big-O formulas you better not to use more complex equations (you might just stick to the ones in the following graph.) However you still might use other more precise formula (like 3^n, n^3, ...) but more than that can be sometimes misleading! So better to keep it as simple as possible.</p>\n\n<p><a href="https://i.stack.imgur.com/ZEmZ6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZEmZ6.png" alt="enter image description here"></a></p>\n\n<p>I would like to emphasize once again that here we don\'t want to get an exact formula for our algorithm. We only want to show how it grows when the inputs are growing and compare with the other algorithms in that sense. Otherwise you would better use different methods like bench-marking.</p>\n'}, {'answer_id': 68223915, 'author': 'Top-Master', 'author_id': 8740349, 'author_profile': 'https://Stackoverflow.com/users/8740349', 'pm_score': 2, 'selected': False, 'text': '<p>First of all, the accepted answer is trying to explain nice fancy stuff, <br>\nbut I think, <em>intentionally</em> complicating Big-Oh is not the solution,<br>\nwhich programmers (or at least, people like me) search for.</p>\n<h2>Big Oh (in short)</h2>\n<pre class="lang-js prettyprint-override"><code>function f(text) {\n  var n = text.length;\n  for (var i = 0; i &lt; n; i++) {\n    f(text.slice(0, n-1))\n  }\n  // ... other JS logic here, which we can ignore ...\n}\n</code></pre>\n<p>Big Oh of above is f(n) = <strong>O(n!)</strong> where <strong>n</strong> represents <code>number</code> of items in input set,\nand <strong>f</strong> represents <code>operation</code> done per item.</p>\n<hr />\n<p>Big-Oh notation is the asymptotic upper-bound of the complexity of an algorithm.<br>\nIn programming: The assumed worst-case time taken,<br>\nor assumed maximum repeat count of logic, for size of the input.</p>\n<h2>Calculation</h2>\n<p>Keep in mind (from above meaning) that; We just need <strong>worst-case time</strong> and/or <strong>maximum repeat count</strong> affected by <strong>N</strong> (size of input),<br>\nThen take another look at (accepted answer\'s) example:</p>\n<pre class="lang-c prettyprint-override"><code>for (i = 0; i &lt; 2*n; i += 2) {  // line 123\n    for (j=n; j &gt; i; j--) {     // line 124\n        foo();                  // line 125\n    }\n}\n</code></pre>\n<ol>\n<li><p>Begin with this search-pattern:</p>\n<ul>\n<li>Find first line that <strong>N</strong> caused repeat behavior,</li>\n<li>Or caused increase of logic executed,</li>\n<li>But constant or not, ignore anything before that line.</li>\n</ul>\n</li>\n<li><p>Seems line hundred-twenty-three is what we are searching ;-)</p>\n<ul>\n<li>On first sight, line seems to have <code>2*n</code> max-looping.</li>\n<li>But looking again, we see <code>i += 2</code> (and that half is skipped).</li>\n<li>So, max repeat is simply <strong>n</strong>, write it down, like <code>f(n) = O( n </code> but don\'t close parenthesis yet.</li>\n</ul>\n</li>\n<li><p>Repeat search till method\'s end, and find next line matching our search-pattern, here that\'s line 124</p>\n<ul>\n<li>Which is tricky, because strange condition, and reverse looping.</li>\n<li>But after remembering that we just need to consider maximum repeat count (or worst-case time taken).</li>\n<li>It\'s as easy as saying &quot;Reverse-Loop <code>j</code> starts with <code>j=n</code>, am I right? yes, <strong>n</strong> seems to be maximum possible repeat count&quot;, so:\n<ul>\n<li>Add <code>n</code> to previous write down\'s end,</li>\n<li>but like &quot;<code>( n </code>&quot;  instead of &quot;<code>+ n</code>&quot; (as this is inside previous loop),</li>\n<li>and close parenthesis only if we find something outside of previous loop.</li>\n</ul>\n</li>\n</ul>\n</li>\n</ol>\n<p>Search Done! why? because line 125 (or any other line after) does not match our search-pattern.<br>\nWe can now close any parenthesis (left-open in our write down), resulting in below:</p>\n<pre><code>f(n) = O( n( n ) )\n</code></pre>\n<p>Try to further shorten &quot;<code>n( n )</code>&quot; part, like:</p>\n<ul>\n<li><strong>n( n ) = n * n</strong></li>\n<li><strong>= n<sup>2</sup></strong></li>\n<li>Finally, just wrap it with Big Oh notation, like <strong>O(n<sup>2</sup>)</strong> or O(n^2) without formatting.</li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/3255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46/']