The idea behind calculating time complexity is how many time your loop/function is executing each step inside of it ?
for example: for loop
for ( int i=0; i < n; i++ ) {
cout << "hello" << endl;
}
the code in curly braces will print n times hello so the time complexity of this for loop will be O(n)
for ( int i=0; i < n; i++ ) {
cout << "hello" << endl;
}
for ( int i=0; i < n; i++ ) {
cout << "hello" << endl;
}
this will print hello 2 time more than the previous as it have two for loop. time complexity is O(2n). We ignore the constants while computing time complexity so the time complexity will be O(n)
for ( int i=0; i < n; i++ ) {
for ( int j=0; j < n; j++ ) {
cout << "hello" << endl;
}
}
this will print hello n^2 time, why ? because for each outer for loop (i) you execute inner for loop(j) O(n) time. so O(n^2)will be time complexity
read further http://www.geeksforgeeks.org/analysis-of-algorithms-set-4-analysis-of-loops/
n = 5units. What do you expect the total running time to be, 10 units (2*n) or 25 units (n^2)?O( n * worst_runtime_of_both{......})