So say I have an algorithm like this:
void dummy_algorithm(int a[]) {
int center = floor(a.length/2);
//For reference purposes: Loop 1
for(int i = 0; i < center; i++) {
//The best code you've ever seen
}
//Loop 2
for(int j = center + 1; j < a.length; j++) {
//Slightly less awesome code
}
}
It’s pretty basic stuff. I know both loops iterate through one half of the array, thus giving each an (n/2) complexity. However, the total work the method does is obviously O(n).
So, my question is: How do I prove (via a recurrence relation) that this algorithm is O(n)? Or am I wrong on this altogether?
Note: I cannot combine the two loops into one. They preform actions that eventually go into recursive calls. Anything else you can think of isn’t allowed. There are a lot of constraints on this problem.
If you are really looking for a proof that O(x) + O(y) = O(x+y), it would work along these lines:
R1 ∈ O(x) ∧ R2 ∈ O(y)
⇒ ∃ a. R1 < ax ∧ ∃ b. R2 < by
⇒ ∃ a, b. R1 < ax ∧ R2 < by
⇒ ∃ a, b. R1+R2 < ax + by
⇒ ∃ a, b. c=max(a,b) ∧ R1+R2 < cx + cy
⇒ ∃ c. R1+R2 < c(x+y)
⇒ R1+R2 ∈ O(x+y)