Relational operators in C - Time & Space Complexity
Relational operators compare values to decide true or false. We want to see how fast these comparisons run as input changes.
How does the time to compare values grow when we use relational operators in code?
Analyze the time complexity of the following code snippet.
int compare(int a, int b) {
if (a > b) {
return 1;
} else {
return 0;
}
}
This code compares two numbers and returns 1 if the first is greater, otherwise 0.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One relational comparison (a > b)
- How many times: Exactly once per function call
Each time we call this function, it does one comparison no matter the numbers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 comparisons if called 10 times |
| 100 | 100 comparisons if called 100 times |
| 1000 | 1000 comparisons if called 1000 times |
Pattern observation: The number of operations grows directly with how many times the function is called, but each call is just one quick comparison.
Time Complexity: O(1)
This means the comparison takes the same short time no matter what numbers we compare.
[X] Wrong: "Comparing bigger numbers takes longer time."
[OK] Correct: Computers compare numbers in fixed steps regardless of size, so time stays constant.
Understanding that simple comparisons run in constant time helps you reason about bigger programs where many comparisons happen.
"What if we compare two arrays element by element instead of single numbers? How would the time complexity change?"