Comparison operators in C Sharp (C#) - Time & Space Complexity
We want to understand how fast comparison operators run when used in code.
How does the time to compare values change as we do more comparisons?
Analyze the time complexity of the following code snippet.
int[] numbers = {1, 3, 5, 7, 9};
int target = 5;
bool found = false;
foreach (int num in numbers)
{
if (num == target)
{
found = true;
break;
}
}
This code checks if a target number exists in an array by comparing each element.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing each array element to the target using the equality operator.
- How many times: Up to once per element, until the target is found or the array ends.
As the array gets bigger, the number of comparisons can grow too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 comparisons |
| 100 | Up to 100 comparisons |
| 1000 | Up to 1000 comparisons |
Pattern observation: The number of comparisons grows roughly in direct proportion to the array size.
Time Complexity: O(n)
This means the time to complete grows linearly as the number of items to compare increases.
[X] Wrong: "Comparison operators take constant time no matter how many times they run."
[OK] Correct: While one comparison is quick, doing many comparisons adds up, so total time depends on how many comparisons happen.
Understanding how comparison operations add up helps you explain efficiency clearly and shows you know how code runs as data grows.
"What if we used a sorted array and stopped searching early? How would the time complexity change?"