What is the complexity of these three algorithms?

Felix :

I've got an exam on Thursday regarding data structure and algorithms and there was this exam question in the exam from last year, where you have to determine the complexity of three algorithms written with java. Can you help me with these algorithms, maybe with an explanation for your solution that would be really great. Thank you!

My solutions are:

AlgorithmOne: n*log(n) the first loop would run with O(n), the second loop runs with log(n) because the counter variable is doubled within each iteration.

AlgorithmTwo: Does not compile, if it doesn't matter that it won't be compiled with a standard java compiler. It's in O(1) because of the return Statement because this will end the algorithm after 1 iteration.

AlgorithmThree: The complexity of the for-loop would be n because of i++ and n/2 which would become n, the complexity of the recursion would be O(n) because it will be executed n times. To sum up the complexity of algorithmThree should be O(n) because the recursive function is not connected with the loop.

int algorithmOne(int n){
    int sum = 0;
    for(int i = 0; i < n/2; i++){
        for(int j = 1; j <= n/4; j= j *2){
            sum++;
        }
    }
    return sum;
}

int algorithmTwo(int n){
    int sum = 0;
    for(int i = 0; i < n/2; i++){
        for(int j = n; j > 1; j = j/2){
            sum++;
            return sum;
        }
    }
}

int algorithmThree(int n){
    int sum = 0;
    if(n>1){
        sum = algorithmThree(n-1)+1;
    }
    else{ 
        sum = 1;
    }
    for(int i=0; i < n/2; i++){
        sum = sum-1;
    }
    return sum;
}
dSanders :

First two are correct as you have analyzed. But for the third one, you need to look at this recursion call again,

    if(n>1){
        sum = algorithmThree(n-1)+1;
    }

This will get executed as long as n>1. And when it reaches the base condition i.e n=1, the for loop will run n/2 times and then return to the previous recursion call,and then repeat again, which makes the total complexity as O(n*n).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=163847&siteId=1