The Daily Parker

Politics, Weather, Photography, and the Dog

O is for O(n) Notation

Blogging A to ZFor day 15 of the Blogging A-to-Z challenge I want to talk about something that computer scientists use but application developers typically don't.

Longtime readers of the Daily Parker know that I put a lot of stock in having a liberal arts education in general, and having one in my profession in specific. I have a disclosed bias against hiring people with computer science (CS) degrees unless they come from universities with rigorous liberal arts core requirements. Distilled down to the essence, I believe that CS majors at most schools spend too much time on how computers work and not enough time on how people work.

But CS majors do have a lexicon that more liberally-educated developers don't really have. For example, when discussing how well code performs, CS majors use "Big O" notation.

In Big O notation, the O stands for "order of growth," meaning how much time could the algorithm could grow to take up given worst-case inputs.

The simplest notation is O(1), where the code always takes the same amount of time to execute no matter what the inputs are:

int q = 1;
int r = 2;
var s = q + r;

Adding two integers in .NET always takes the same amount of time, no matter what the integers are.

The titular notation for this post, O(n), means that the execution time grows linearly based on the input. Each item you add to the input increases the time the algorithm takes by exactly one unit, as in a simple for loop:

public long LoopExample(int[] numbers)
{
	long sum;
	for(var x = 0; x < numbers.Length; x++)
	{
		sum += numbers[x];
	}
	return sum;
}

In that example, each item you add to the array numbers increases the time the loop takes by exactly one unit of time, whatever that unit may be. (On most computers today that would be measured in units of milliseconds, or even hundreds of nanoseconds.)

Other algorithms may be slower or faster than these examples, except that no algorithm can be faster than O(1). The parenthetical can be any expression of n. Some algorithms grow by the logarithm of n, some grow by the double of n, some grow by the square of n.

This notation enables people to communicate precisely about how well code performs. If you find that your code takes O(n2) time to run, you may want to find a fix that reduces it to O(log n). And you can communicate to people how you increased efficiency in just that way.

So as much as I want application developers to have broad liberal educations, it's worth remembering that computer science fits into a liberal education as well.

Comments are closed