/**
 * Changes the priority of the element at the specified position of the
 * priority queue, maintaining the heap condition of the queue.
 *
 * This function has a time complexity of O(Log N),
 * with N being the number of elements in the queue.
 *
 * @return int rc >= 0: The index of the element after the priority change.
 * @return int rc <  0: An error see pbl_errno:
 *
 * <BR>PBL_ERROR_OUT_OF_BOUNDS - Index is out of range (index < 0 || index >= size()).
 */
int pblPriorityQueueChangePriorityAt( /*                        */
PblPriorityQueue * queue, /** The queue to use                  */
int index, /** The index at which the priority is to be changed */
int priority /** The new priority of the element                */
)
{
    PblPriorityQueueEntry *entry =
            (PblPriorityQueueEntry *)pblHeapGet( (PblHeap *)queue, index );
    if( entry == (PblPriorityQueueEntry *)-1 )
    {
        return -1;
    }

    if( priority < entry->priority )
    {
        int size = pblHeapSize( (PblHeap *)queue );

        entry->priority = priority;

        // For zero based arrays all entries with an index bigger
        // than 'size / 2 - 1' do not have any children.
        //
        // Decreasing the priority cannot violate the heap condition
        // for entries with no children
        //
        if( index <= size / 2 - 1 )
        {
            // The heap condition only needs to be ensured
            // if the entry has children
            //
            return pblHeapEnsureCondition( queue, index );
        }
    }
    else if( priority > entry->priority )
    {
        entry->priority = priority;

        // Increasing the priority cannot violate the heap condition
        // for the top entry at index 0
        //
        if( index > 0 )
        {
            // The heap condition needs to ensured
            //
            return pblHeapEnsureCondition( queue, index );
        }
    }

    return index;
}
Example #2
0
/**
 * Inserts the element with the specified priority into the
 * priority queue and maintains the heap condition
 * of the priority queue.
 *
 * This function has a time complexity of O(Log N),
 * with N being the number of elements in the queue.
 *
 * @return int rc >= 0: The size of the queue.
 * @return int rc <  0: An error, see pbl_errno:
 *
 * <BR>PBL_ERROR_OUT_OF_MEMORY - Out of memory.
 */
int pblPriorityQueueInsert( /*                           */
PblPriorityQueue * queue, /** The queue to use           */
int priority, /** Priority of the element to be inserted */
void * element /** Element to be inserted to the queue   */
)
{
	// Add to the end of the queue
	//
	int rc = pblPriorityQueueAddLast(queue, priority, element);
	if (rc > 1)
	{
		// Ensure the heap condition for the last entry
		//
		pblHeapEnsureCondition(queue, rc - 1);
	}
	return rc;
}