与前一篇堆的实现相关。
此页代码未经调试!
//priority queue
int HeapMaximum( int *heap, int heapSize )
{
return heap[heapSize - 1];
}
int HeapExtractMax( int *heap, int heapSize )
{
if ( heapSize < 1 )
{
cout << "heap underflow!" << endl;
return -1;
}
int max = heap[0];
heap[0] = heap[heapSize - 1];
--heapSize;
MaxHeapify( heap, 0, heapSize );
return max;
}
int HeapIncreaseKey( int *heap, int index, int key, int heapSize )
{
if ( key < heap[index] )
{
cout << "The new key is smaller than current key!";
return -1;
}
heap[index] = key;
int parent = (index - 1) / 2;
if ( heap[index] <= heap[parent] )
{
return 0;
}
else
{
while ( index > 0 && heap[index] > heap[parent] )
{
int temp = heap[parent];
heap[parent] = heap[index];
heap[index] = temp;
index = parent;
parent = (index - 1) / 2;
}
}
return 0;
}
int* MaxHeapInsert( int *heap, int key, int heapSize )
{
int *newHeap = new int[heapSize + 1];
for ( int i = 0; i < heapSize; ++i )
{
newHeap[i] = heap[i];
}
delete [] heap;
newHeap[heapSize] = INT_MIN;
++heapSize;
HeapIncreaseKey( newHeap, heapSize - 1, key, heapSize );
return newHeap;
}
本文介绍了一个最大堆的数据结构实现,包括获取最大元素、提取最大元素、增加键值以及插入新元素等关键操作,并提供了相应的C++代码实现。
1067

被折叠的 条评论
为什么被折叠?



