Let's say we have an algorithm that goes through a list of n numbers twice and counts the number of the ones above 50 in one run and the ones below 50 in the other run and stores these in two variables. If we change it to do the same in one run by incrementing not just one but either of the variables in each step, do we change time complexity of the algorithm? Do we consider the new one faster?
I know it will require less steps but not exactly sure about time complexity notation.
EDIT:
Pseudocode 1:
for (i = 0; i < TOTAL_NUMBERS; i++) {
if (numbers[i] >= 50) {
greaterThan50++;
}
}
for (i = 0; i < TOTAL_NUMBERS; i++) {
if (numbers[i] < 50) {
lessThan50++;
}
}
Pseudocode 2:
for (i = 0; i < TOTAL_NUMBERS; i++) {
if (numbers[i] >= 50) {
greaterThan50++;
}
else {
lessThan50++;
}
}
Something is simple if you can obtain the same result but with smallest expression posible. So in this case if you combine the update of the two counters in the same loop the algorithm will need less CPU cycles to be executed. You can also save time in the number validation cause you can just make one if / else statement to do what you need.
A pseudocode could look like this:
If you want to exclude the numbers that are equal 50 you can do something like:
As you might notice in this last example you are doing an extra validation so it will take an extra step, but this algorithm will still be much faster than looping through the list twice (and also simpler since it requires less lines of code and makes the code more readable and easy to understand).
I hope this helps with your question :)