It is strange to try to evaluate time complexity of printf()
as it's a blocking input/output operation that performs some text processing and performs a write operation via a series of write()
system calls through an intermediate buffering layer.
The best guess about the text processing part is that the whole input string must be read and all arguments are processed so unless there's some black magic, you can assume O(n) to the number of characters. You're usually not expected to feed the format argument of printf()
dynamicaly and therefore the size is known, therefore finite and therefore the complexity is indeed O(1).
On the other hand, the time complexity of a blocking output operation is not bounded. In blocking mode, all write()
operations return either with an error or with at least one byte written. Assuming the system is ready to accept new data in a constant time, you're getting O(1) as well.
Any other transformations also occur lineary to the typically constant size of the format or result string, so with a number of assumptions, you can say it's O(1).
Also your code suggests that the output only occurs to actually test the functionality and shouldn't be considered part of the computation at all. The best way is to move the I/O out of the functions you want to consider for the purpose of complexity, e.g. to the main()
function to stress that the input and output is there just for testing out the code.
Implementation of the O(1) swap function without I/O:
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
Alternative implementation without a temporary variable (just for fun):
void swap(int *a, int *b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
Implementation of the main function:
int main(int argc, char **argv)
{
int a = 3, b = 5;
printf("a = %d; b = %d\n", a, b);
swap(&a, &b);
printf("a = %d; b = %d\n", a, b);
return 0;
}