Jump to content

Big-O Question

Featured Replies

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)?

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.

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)

Archived

This topic is now archived and is closed to further replies.

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.