【发布时间】:2014-03-06 06:34:55
【问题描述】:
我有一个将元素插入优先级队列的方法。我想知道它的表演时间。
如果插入的元素可以放在队列的底部,我相信它可以是 O(1)。但是,如果要插入的元素是新的最小值并且一直渗透到根,它会在 O(log N) 时间运行。 这个推理正确吗?
这里是方法插入方法:
/**
* Insert into the priority queue, maintaining heap order.
* Duplicates are allowed.
* @param x the item to insert.
*/
public void insert( AnyType x )
{
if( currentSize == array.length - 1 )
enlargeArray( array.length * 2 + 1 );
// Percolate up
int hole = ++currentSize;
for( array[ 0 ] = x; x.compareTo( array[ hole / 2 ] ) < 0; hole /= 2 )
array[ hole ] = array[ hole / 2 ];
array[ hole ] = x;
}
【问题讨论】:
-
现在是 O(n),因为
enlargeArray是 O(n)。 -
@LuiggiMendoza,是的,但仅限于最坏的情况。摊销时间为 O(log N)。
-
@mkrakhin 是的,但 OP 并没有要求摊销时间。
标签: java queue complexity-theory time-complexity priority-queue