Jump to content

Recommended Posts

Posted

Hello,

 

First post here. Question is in regards to Big-O. I'm wondering if a method calls another method which is O(n), does this method become O(n) as well. If not, why not? It seems that it should be.

 

Here's an example (and my professor marked this as O(1), but it calls an O(n))

 

 

public void push (T element)

{

if (size() == stack.length)

expandCapacity();

 

stack[top] = element;

top++;

}

 

private void expandCapacity()

{

T[] larger = (T[])(new Object[stack.length*2]);

 

for (int index=0; index < stack.length; index++)

larger[index] = stack[index];

 

stack = larger;

}

 

So why is the push function not O(n)?

Posted

Hello,

 

First post here. Question is in regards to Big-O. I'm wondering if a method calls another method which is O(n), does this method become O(n) as well. If not, why not? It seems that it should be.

 

Here's an example (and my professor marked this as O(1), but it calls an O(n))

 

 

public void push (T element)

{

if (size() == stack.length)

expandCapacity();

 

stack[top] = element;

top++;

}

 

private void expandCapacity()

{

T[] larger = (T[])(new Object[stack.length*2]);

 

for (int index=0; index < stack.length; index++)

larger[index] = stack[index];

 

stack = larger;

}

 

So why is the push function not O(n)?

 

 

expandCapacity() is O(n), but it doubles the capacity of the stack when called.

size() == stack.length

will only return true on average 1/n times.

Posted

public void push (T element)
{
      if (size() == stack.length) 
             expandCapacity();

      stack[top] = element;
      top++;
}

private void expandCapacity()
{
      T[] larger = (T[])(new Object[stack.length*2]);

      for (int index=0; index < stack.length; index++)
             larger[index] = stack[index];

      stack = larger;
}

 

the function top complexity is not O(1), it's O(g(x)) .. where g(x) = complexity of expandCapacity = O(n)

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.