Esempio n. 1
0
void bubble_down(Queue *q, int bubbleThis) {
    // base case this is the largest element
    if(q->nextIndex <= leftId(bubbleThis))
        return;
    // find the smallest priority child and swap this with it
    // we know we have at least a left child so that is the curent min
    int minChildId = leftId(bubbleThis);

    // calculate the right child id (if there is one)
    int rid = rightId(bubbleThis);
    // if there is a right child and the priority of it is less than our curent min
    if(q->nextIndex > rid && q->array[rid].priority < q->array[minChildId].priority)
        // then this is our new min child
        minChildId = rid;

    // if our smallest child is a lower priority then swap
    if(q->array[bubbleThis].priority>q->array[minChildId].priority) {
        swap(q, bubbleThis, minChildId);
        bubble_down(q, minChildId);
    }
}
Esempio n. 2
0
//from A[i]->leaf, to make A[i] at the correct position
void maxHeapify(int i) 
{
	int l = leftId(i);
	int r = rightId(i);
	
	int largest;
	// if leftId child is larger than current, then 
	if( l<=heap_size && number[l]>number[i] )
		largest = l;
	else
		largest = i;
		
	// if rightId child is larger than current, then 
	if( r<=heap_size && number[r]>number[largest] )
		largest = r;
	
	if( largest!=i )	
	{
		//swap and 
		std::swap( number[i], number[largest] );
		maxHeapify(largest);
	}
}