## Algorithm – The Time Complexity

Ever wondered What is time complexity of any algorithm & How to calculate it?

Well Time complexity of an algorithm signifies the total time required by the program to run till its completion.

### How to Calculate?

The most common measure for calculating time complexity is Big O notation. This removes all constant factors so that the running time can be estimated in relation to N as N approaches infinity. In general you can think of it like this:

1. `statement;`

Is constant. The running time of the statement will not change in relation to N.

1. `for ( i = 0; i < N; i++ )`
2. ` statement;`

Is linear. The running time of the loop is directly proportional to N. When N doubles, so does the running time.

1. `for ( i = 0; i < N; i++ ) {`
2. ` for ( j = 0; j < N; j++ )`
3. ` statement;`
4. `}`

Is quadratic. The running time of the two loops is proportional to the square of N. When N doubles, the running time increases by N * N.

1. `while ( low <= high ) {`
2. ` mid = ( low + high ) / 2;`
3. ` if ( target < list[mid] )`
4. ` high = mid - 1;`
5. ` else if ( target > list[mid] )`
6. ` low = mid + 1;`
7. ` else break;`
8. `}`

Is logarithmic. The running time of the algorithm is proportional to the number of times N can be divided by 2. This is because the algorithm divides the working area in half with each iteration.

1. `void quicksort ( int list[], int left, int right )`
2. `{`
3. ` int pivot = partition ( list, left, right );`
4. ` quicksort ( list, left, pivot - 1 );`
5. ` quicksort ( list, pivot + 1, right );`
6. `}`

Is N * log ( N ). The running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm is a combination of linear and logarithmic.

In general, doing something with every item in one dimension is linear, doing something with every item in two dimensions is quadratic, and dividing the working area in half is logarithmic. There are other Big O measures such as cubic, exponential, and square root, but they’re not nearly as common. Big O notation is described as O ( <type> ) where <type> is the measure. The quicksort algorithm would be described as O ( N * log ( N ) ).

Note that none of this has taken into account best, average, and worst case measures. Each would have its own Big O notation. Also note that this is a VERY simplistic explanation. Big O is the most common, but it’s also more complex that I’ve shown. There are also other notations such as big omega, little o, and big theta. You probably won’t encounter them outside of an algorithm analysis course.

## One thought on “Algorithm – The Time Complexity”

1. Michaelslell says:

Hi, i think that i saw you visited my web site thus i came to “return the favor”.I am attempting to find things to enhance my site!I suppose its ok to use some of your ideas!!