开发者

What's the complexity (bigO) of this algorithm?

开发者 https://www.devze.com 2023-02-25 08:46 出处:网络
This algorithm look开发者_Go百科s through a string and tries to find another string. The logic is simple, I guess. Though, I need help finding it\'s complexity.

This algorithm look开发者_Go百科s through a string and tries to find another string. The logic is simple, I guess. Though, I need help finding it's complexity.

int find(string mString, string lookUp)
{
    int i, z, j, m = mString.size(), n = lookUp.size(), broken = 0, st = 0;
    for(j = 0, i = 0; i < m; i++)
    {
        if(mString[i] == lookUp[j])
        {
            if(broken)
            {
                //go back and see if we're on the good path
                broken = 0;
                for(z = 0; z < j; z++)
                {
                    if(broken) break;
                    if(mString[i-z] == lookUp[j-z])
                        broken = 0;
                    else
                        broken = 1;
                }
                if(!broken) st = i - j + 1;
            }
            if(j + 1 != n)
                j++;
        }
        else
            broken = 1;
    }
    return st;
}

Can somebody please help me?

Thank you.


When dealing with big-O and loops, I ask myself the question:

How many times, at most, can each loop run?

In your example,

  1. The outer loop will run, at most, `m` times.
  2. The inner loop will run, at most, `n` times.
  3. For each iteration of the outer loop, the inner loop will run, at most, `n` times

Does this help clarify your thinking?


O(n^2) is the final complexity of this algorithm.

0

精彩评论

暂无评论...
验证码 换一张
取 消