What time-complexity will the following code have in respect to the parameter size? Motivate.
// Process(A, N) is O(sqrt(N)).
Function Complex(array[], size){
if(size == 1) return 1;
if(rand() / float(RAND_MAX) < 0.1){
return Process(array, size*size)
+ Complex(array, size/2)
+ Process(array, size*size);
}
}
I think it is O(N), because if Process(A, N) is O(sqrt(N)), then Process(A, N*N) should be O(N), and Complex(array, size/2) is O(log(n)) because it halves the size every time it runs. So on one run it takes O(N) + O(log(N)) + O(N) = O(N).
Please correct me and give me some hints on how I should think / proceed an assignment like this.
I appreciate all help and thanks in advance.
The time complexity of the algorithm is
O(N)indeed, but for a different reason.The complexity of the function can be denoted as
T(n)where:This recursion is well known to be O(n):
Let’s formally prove it, we will use mathematical induction for it:
Base: T(1) < 4 (check)
Hypothesis: For
n, and for everyk<nthe claimT(k) < 4kholds true.For
n:Conclusion:
T(n)is inO(n)(*) From the induction hypothesis