2008-08-06 10:18:16 8 Comments

Most people with a degree in CS will certainly know what Big O stands for. It helps us to measure how well an algorithm scales.

But I'm curious, how do *you* calculate or approximate the complexity of your algorithms?

### Related Questions

#### Sponsored Content

#### 41 Answered Questions

### [SOLVED] What is a plain English explanation of "Big O" notation?

**2009-01-28 11:10:32****Arec Barrwin****704241**View**4969**Score**41**Answer- Tags: algorithm complexity-theory computer-science big-o time-complexity

#### 53 Answered Questions

### [SOLVED] How do I check if an array includes a value in JavaScript?

**2008-10-25 22:14:40****brad****2608709**View**4060**Score**53**Answer- Tags: javascript arrays algorithm time-complexity javascript-objects

#### 41 Answered Questions

### [SOLVED] How can you speed up Eclipse?

**2008-11-25 03:18:56****user2427****610458**View**1277**Score**41**Answer- Tags: eclipse performance

#### 9 Answered Questions

### [SOLVED] How to find time complexity of an algorithm

**2012-06-14 11:21:15****Yasser Shaikh****693769**View**904**Score**9**Answer- Tags: algorithm time-complexity complexity-theory

#### 47 Answered Questions

#### 36 Answered Questions

### [SOLVED] How can I pair socks from a pile efficiently?

**2013-01-19 15:34:35****amit****412900**View**3927**Score**36**Answer- Tags: algorithm sorting language-agnostic matching

#### 10 Answered Questions

### [SOLVED] Improve INSERT-per-second performance of SQLite

**2009-11-10 22:16:43****Mike Willekes****404888**View**3016**Score**10**Answer- Tags: c performance sqlite optimization

#### 11 Answered Questions

### [SOLVED] Computational complexity of Fibonacci Sequence

**2008-12-11 20:20:25****Juliet****310534**View**334**Score**11**Answer- Tags: time-complexity big-o complexity-theory fibonacci

#### 24 Answered Questions

### [SOLVED] Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

**2012-04-16 04:23:16****Charles Menguy****192632**View**1673**Score**24**Answer- Tags: c++ algorithm image-processing opencv

## 23 comments

## @Samy Bencherif 2016-08-20 04:57:30

great question!

Disclaimer: this answer contains false statements see the comments below.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.

Check out this site for a lovely formal definition of Big O: https://xlinux.nist.gov/dads/HTML/bigOnotation.html

Ok, so now what do we mean by "best-case" and "worst-case" complexities?

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

worst caseis when we decide tosearch for the last elementof the array as this would take as many steps as there are items in the array. Thebest casewould be when we search for thefirst elementsince we would be done after the first check.The point of all these

adjective-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 withmultiplefunctions 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.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.

## @Samy Bencherif 2017-12-11 06:10:44

This is incorrect. Big O means "upper bound" not worst case.

## @Bernhard Barker 2017-12-24 14:10:44

It's a common misconception that big-O refers to worst-case. How do O and Ω relate to worst and best case?

## @Tasneem Haider 2019-03-02 19:01:41

This is misleading. Big-O means upper bound for a function f(n). Omega means lower bound for a function f(n). It is not at all related to best case or worst case.

## @Samy Bencherif 2019-03-02 20:21:21

You can use Big-O as an upper bound for either best or worst case, but other than that, yes no relation.

## @vz0 2011-01-31 15:33:54

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 Data Structures and Algorithms in Java book.

There is no mechanical procedure that can be used to get the BigOh.

As a "cookbook", to obtain the BigOh 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.

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.

For example, let's say you have this piece of code:

This function returns the sum of all the elements of the array, and we want to create a formula to count the computational complexity of that function:

So we have

`f(N)`

, 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:The parameter

`N`

takes the`data.length`

value. Now we need the actual definition of the function`f()`

. This is done from the source code, in which each interesting line is numbered from 1 to 4.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

`C`

number computational steps.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

`data`

array.That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this:

The next part is to define the value of the

`for`

statement. Remember that we are counting the number of computational steps, meaning that the body of the`for`

statement gets executed`N`

times. That's the same as adding`C`

,`N`

times:There is no mechanical rule to count how many times the body of the

`for`

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`for`

statement.To get the actual BigOh we need the Asymptotic analysis of the function. This is roughly done like this:

`C`

.`f()`

get the polynomium in its`standard form`

.`N`

approaches`infinity`

.Our

`f()`

has two terms:Taking away all the

`C`

constants and redundant parts:Since the last term is the one which grows bigger when

`f()`

approaches infinity (think on limits) this is the BigOh argument, and the`sum()`

function has a BigOh of:There are a few tricks to solve some tricky ones: use summations whenever you can.

As an example, this code can be easily solved using summations:

The first thing you needed to be asked is the order of execution of

`foo()`

. While the usual is to be`O(1)`

, you need to ask your professors about it.`O(1)`

means (almost, mostly) constant`C`

, independent of the size`N`

.The

`for`

statement on the sentence number one is tricky. While the index ends at`2 * N`

, the increment is done by two. That means that the first`for`

gets executed only`N`

steps, and we need to divide the count by two.The sentence number

twois even trickier since it depends on the value of`i`

. Take a look: the index i takes the values: 0, 2, 4, 6, 8, ..., 2 * N, and the second`for`

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`for`

never gets executed.On formula, that means:

Again, we are counting

the number of steps. And by definition, every summation should always start at one, and end at a number bigger-or-equal than one.(We are assuming that

`foo()`

is`O(1)`

and takes`C`

steps.)We have a problem here: when

`i`

takes the value`N / 2 + 1`

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`i`

takes`N / 2 + 1`

.Since the pivotal moment

`i > N / 2`

, the inner`for`

won't get executed, and we are assuming a constant C execution complexity on its body.Now the summations can be simplified using some identity rules:

`w`

)Applying some algebra:

And the BigOh is:

## @Abhishek Dey Das 2014-11-14 20:34:47

@arthur That would be O(N^2) because you would require one loop to read through all the columns and one to read all rows of a particular column.

## @Mooing Duck 2015-04-06 22:55:57

@arthur: It depends. It's

`O(n)`

where`n`

is the number of elements, or`O(x*y)`

where`x`

and`y`

are the dimensions of the array. Big-oh is "relative to the input", so it depends on what is your input.## @Parsa 2015-11-19 11:35:52

Great answer, but I am really stuck. How does Summation(i from 1 to N / 2)( N ) turns into ( N ^ 2 / 2 ) ?

## @Mario Carneiro 2015-11-24 14:26:36

@ParsaAkbari As a general rule, sum(i from 1 to a) (b) is a * b. This is just another way of saying b+b+...(a times)+b = a * b (by definition for some definitions of integer multiplication).

## @Albert 2016-02-12 13:12:37

Not so relevant, but just to avoid confusion, there is a tiny mistake in this sentence: "the index i takes the values: 0, 2, 4, 6, 8, ..., 2 * N". Index i actually goes up to 2 * N - 2, the loop will stop then.

## @Albert 2016-02-12 13:30:19

Well, the same kind of problem presents itself again later, if you think it's worth having a look at it.

## @HmT 2019-02-20 10:44:36

I would like to explain the Big-O in a little bit different aspect.

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.

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.

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.

## @laynece 2011-01-31 20:07:35

For code A, the outer loop will execute for

`n+1`

times, the '1' time means the process which checks the whether i still meets the requirement. And inner loop runs`n`

times,`n-2`

times.... Thus,`0+2+..+(n-2)+n= (0+n)(n+1)/2= O(n²)`

.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)

## @Mike Dunlavey 2009-03-10 13:24:13

I think about it in terms of information. Any problem consists of learning a certain number of bits.

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

_{2}of the inverse probability of that branch. That's how much you learn by executing that decision.For example, an

`if`

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.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.

That's what you get with binary search.

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.

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.

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.

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.

I've found that nearly all algorithmic performance issues can be looked at in this way.

## @Jesvin Jose 2011-09-11 08:43:37

Wow. Do you have any helpful references on this? I feel this stuff is helpful for me to design/refactor/debug programs.

## @Mike Dunlavey 2011-09-11 13:47:26

@aitchnyu: For what it's worth, I wrote a book covering that and other topics. It's long since out of print, but copies are going for a reasonable price. I've tried to get GoogleBooks to grab it, but at the moment it's a little hard to figure out who's got the copyright.

## @Giovanni Galbo 2008-09-05 19:09:48

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.

Here are some of the most common cases, lifted from http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions:

O(1) - Determining if a number is even or odd; using a constant-size lookup table or hash table

O(logn) - Finding an item in a sorted array with a binary search

O(n) - Finding an item in an unsorted list; adding two n-digit numbers

O(n

^{2}) - Multiplying two n-digit numbers by a simple algorithm; adding two n×n matrices; bubble sort or insertion sortO(n

^{3}) - Multiplying two n×n matrices by simple algorithmO(c

^{n}) - Finding the (exact) solution to the traveling salesman problem using dynamic programming; determining if two logical statements are equivalent using brute forceO(n!) - Solving the traveling salesman problem via brute-force search

O(n

^{n}) - Often used instead of O(n!) to derive simpler formulas for asymptotic complexity## @Samy Bencherif 2017-12-11 06:15:14

Why not use

`x&1==1`

to check for oddness?## @ShadowRanger 2019-03-21 14:42:39

@SamyBencherif: That would be a typical way to check (actually, just testing

`x & 1`

would be sufficient, no need to check`== 1`

; in C,`x&1==1`

is evaluated as`x&(1==1)`

thanks to operator precedence, so it's actually the same as testing`x&1`

). I think you're misreading the answer though; there is a semi-colon there, not a comma. It's not saying you'd need a lookup table for even/odd testing, it's saying both even/odd testingandchecking a lookup table are`O(1)`

operations.## @conditionalMethod 2019-09-26 17:52:28

I don't know about the claim on usage in the last sentence, but whoever does that is replacing a class by another that is not equivalent. The class O(n!) contains, but is strictly larger than O(n^n). The actual equivalence would be O(n!) = O(n^ne^{-n}sqrt(n)).

## @OysterD 2008-08-23 20:43:50

Small reminder: the

`big O`

notation is used to denoteasymptoticcomplexity (that is, when the size of the problem grows to infinity),andit hides a constant.This means that between an algorithm in O(n) and one in O(n

^{2}), 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).Note that the hidden constant very much depends on the implementation!

Also, in some cases, the runtime is not a deterministic function of the

sizen 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.There are different time complexities:

Average case (usually much harder to figure out...)

...

A good introduction is

An Introduction to the Analysis of Algorithmsby R. Sedgewick and P. Flajolet.As you say,

`premature optimisation is the root of all evil`

, and (if possible)profilingreally should always be used when optimising code. It can even help you determine the complexity of your algorithms.## @Douglas Zare 2015-02-26 13:59:40

In mathematics, O(.) means an upper bound, and theta(.) means you have a bound above and below. Is the definition actually different in CS, or is it just a common abuse of notation? By the mathematical definition, sqrt(n) is both O(n) and O(n^2) so it is not always the case that there is some n after which an O(n) function is smaller.

## @ajknzhol 2014-02-02 15:30:25

Lets start from the beginning.

First of all, accept the principle that certain simple operations on data can be done in

`O(1)`

time, that is, in time that is independent of the size of the input. These primitive operations in C consist ofThe 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. As a consequence, several kinds of statements in C can be executed in

`O(1)`

time, that is, in some constant amount of time independent of input. These simple includeIn C, many for-loops are formed by initializing an index variable to some value and incrementing that variable by 1 each time around the loop. The for-loop ends when the index reaches some limit. For instance, the for-loop

uses index variable i. It increments i by 1 each time around the loop, and the iterations stop when i reaches n − 1.

However, for the moment, focus on the simple form of for-loop, where the

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. 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.For instance, the for-loop iterates

`((n − 1) − 0)/1 = n − 1 times`

, since 0 is the initial value of i, n − 1 is the highest value reached by i (i.e., when i reaches n−1, the loop stops and no iteration occurs with i = n−1), and 1 is added to i at each iteration of the loop.In the simplest case, where the time spent in the loop body is the same for each iteration,

we can multiply the big-oh upper bound for the body by the number of times around the loop. Strictly speaking, we must thenadd O(1) time to initialize the loop index and O(1) time for the first comparison of the loop index with the limit, because we test one more time than we go around the loop. However, unless it is possible to execute the loop zero times, the time to initialize the loop and test the limit once is a low-order term that can be dropped by the summation rule.Now consider this example:

We know that

line (1)takes`O(1)`

time. Clearly, we go around the loop n times, as we can determine by subtracting the lower limit from the upper limit found on line (1) and then adding 1. Since the body, line (2), takes O(1) time, we can neglect the time to increment j and the time to compare j with n, both of which are also O(1). Thus, the running time of lines (1) and (2) is theproduct of n and O(1), which is`O(n)`

.Similarly, we can bound the running time of the outer loop consisting of lines (2) through (4), which is

We have already established that the loop of lines (3) and (4) takes O(n) time. Thus, we can neglect the O(1) time to increment i and to test whether i < n in each iteration, concluding that each iteration of the outer loop takes O(n) time.

The initialization i = 0 of the outer loop and the (n + 1)st test of the condition i < n likewise take O(1) time and can be neglected. Finally, we observe that we go around the outer loop n times, taking O(n) time for each iteration, giving a total

`O(n^2)`

running time.A more practical example.

## @Taha Tariq 2018-03-10 05:38:46

What if a goto statement contains a function call?Something like step3: if (M.step == 3) { M = step3(done, M); } step4: if (M.step == 4) { M = step4(M); } if (M.step == 5) { M = step5(M); goto step3; } if (M.step == 6) { M = step6(M); goto step4; } return cut_matrix(A, M); how would the complexity be calculated then? would it be an addition or a multiplication?considering step4 is n^3 and step5 is n^2.

## @Gavriel Feria 2013-05-11 01:32:45

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:

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 . . . .

## @Martin 2008-09-23 07:26:08

Less useful generally, I think, but for the sake of completeness there is also a Big Omega Ω, which defines a lower-bound on an algorithm's complexity, and a Big Theta Θ, which defines both an upper and lower bound.

## @Matt Mitchell 2008-08-06 10:59:40

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 IntelliSense.

## @sven 2008-08-07 08:10:04

Seeing the answers here I think we can conclude that most of us do indeed approximate the order of the algorithm by

lookingat it and use common sense instead of calculating it with, for example, the master method as we were thought at university. With that said I must add that even the professor encouraged us (later on) to actuallythinkabout it instead of just calculating it.Also I would like to add how it is done for

recursive functions:suppose we have a function like (scheme code):

which recursively calculates the factorial of the given number.

The first step is to try and determine the performance characteristic for

the body of the function onlyin this case, nothing special is done in the body, just a multiplication (or the return of the value 1).So the

performance for the body is: O(1)(constant).Next try and determine this for the

number of recursive calls. In this case we have n-1 recursive calls.So the

performance for the recursive calls is: O(n-1)(order is n, as we throw away the insignificant parts).Then put those two together and you then have the performance for the whole recursive function:

1 * (n-1) = O(n)Peter, to answer your raised issues; the method I describe here actually handles this quite well. But keep in mind that this is still an

approximationand 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.Of 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.

## @Peteter 2008-08-15 05:46:56

Sven, I'm not sure that your way of judging the complexity of a recursive function is going to work for more complex ones, such as doing a top to bottom search/summation/something in a binary tree. Sure, you could reason about a simple example and come up with the answer. But i figure you'd have to actually do some math for recursive ones?

## @TT_ 2014-01-19 03:09:58

+1 for the recursion... Also this one is beautiful: "...even the professor encouraged us to think..." :)

## @Abhinav Gauniyal 2015-04-22 16:54:33

Yes this is so good. I tend to think it like this , higher the term inside O(..) , more the work you're / machine is doing. Thinking it while relating to something might be an approximation , but so are these bounds. They just tell you how does the work to be done increases when number of inputs are increased.

## @Emmanuel 2011-01-31 14:36:02

For the 1st case, the inner loop is executed

`n-i`

times, so the total number of executions is the sum for`i`

going from`0`

to`n-1`

(because lower than, not lower than or equal) of the`n-i`

. You get finally`n*(n + 1) / 2`

, so`O(n²/2) = O(n²)`

.For the 2nd loop,

`i`

is between`0`

and`n`

included for the outer loop; then the inner loop is executed when`j`

is strictly greater than`n`

, which is then impossible.## @Marcelo Cantos 2011-01-31 13:30:15

If your cost is a polynomial, just keep the highest-order term, without its multiplier. E.g.:

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:

## @jk. 2011-01-31 13:52:40

surely O(N) < O(NlogN)

## @Suma 2009-03-10 15:02:13

As to "how do you calculate" Big O, this is part of Computational complexity theory. 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.

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 Amortized analysis very useful in practice.

## @Baltimark 2009-03-10 14:30:13

What often gets overlooked is the

expectedbehavior of your algorithms.It doesn't change the Big-O of your algorithm, but it does relate to the statement "premature optimization. . .."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.

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.

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.

## @John D. Cook 2008-12-11 20:49:05

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.

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.

## @Christopher John 2018-11-28 12:43:45

Just to update this answer: en.wikipedia.org/wiki/Analysis_of_algorithms, this link has the formula you need. Many algorithms follow a power rule, if yours does, with 2 timepoints and 2 runtimes on a machine, we can calculate the slope on a log-log plot. Which is a=log(t2/t1)/log(n2/n1), this gave me the exponent for the algorithm in, O(N^a). This can be compared versus manual calculation using the code.

## @agenis 2019-01-22 13:19:30

Hi, nice answer. I was wondering if you are aware of any library or methodology (i work with python/R for instance) to generalize this empirical method, meaning like fitting various complexity functions to increasing size dataset, and find out which is relevant. Thanks

## @JB King 2008-10-14 20:16:38

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.

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.

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.

## @Eric 2008-09-05 18:33:32

In addition to using the master method (or one of its specializations), I test my algorithms experimentally. This can't

provethat 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.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.

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.

## @Adam 2008-08-14 15:35:50

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.

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...)

## @kelalaka 2018-09-30 22:02:44

Depends on the loops.

## @Pall Melsted 2008-08-08 13:53:20

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.

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.

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.

Therefore we can upper bound the amount of work by O(n*log(n)).

However, Big O hides some details which we sometimes can't ignore. Consider computing the Fibonacci sequence with

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.

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

1 + 2 + 3 + ... + n = n(n-1)/2 = O(n^2)

So this algorithm runs in quadradic time!

## @mikek3332002 2010-07-23 03:40:19

You shouldn't care about how the numbers are stored, it doesn't change that the algorithm grows at an upperbound of O(n).

## @DShook 2008-08-06 13:34:13

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.

A few examples of how it's used in C code.

Say we have an array of n elements

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.

If we wanted to find a number in the list:

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).

When we get to nested loops:

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.

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.

## @Navaneeth K N 2009-07-31 04:29:52

Great explanation! So if someone says his algorithm has a O(n^2) complexity, does it mean he will be using nested loops?

## @asyncwait 2009-10-09 11:21:42

Not really, any aspect that lead to n squared times will be considered as n^2

## @ShadowRanger 2019-03-21 14:36:53

@NavaneethKN: You won't always

seethe nested loop, as function calls can do >`O(1)`

work themselves. In the C standard APIs for instance,`bsearch`

is inherently`O(log n)`

,`strlen`

is`O(n)`

, and`qsort`

is`O(n log n)`

(technically it has no guarantees, and quicksort itself has a worst case complexity of`O(n²)`

, but assuming your`libc`

author isn't a moron, its average case complexity is`O(n log n)`

and it uses a pivot selection strategy that reduces the odds of hitting the`O(n²)`

case). And both`bsearch`

and`qsort`

can be worse if the comparator function is pathological.## @Lasse V. Karlsen 2008-08-06 11:34:26

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.

For more information, check the Wikipedia page on the subject.