堆的基本操作
堆的基本操作(创建大根堆,插入,删除及排序)#include <iostream>using namespace std;//将元素key向下调整void AdjustDown(int heap[], int top, int len){heap[0]=heap[top];for(int i=2*top; i<=len; i*=2)
·
堆的基本操作(创建大根堆,插入,删除及排序)
#include <iostream>
using namespace std;
//将顶端元素向下调整
void AdjustDown(int heap[], int top, int len)
{
heap[0]=heap[top];
for(int i=2*top; i<=len; i*=2)
{
if(i<len&&heap[i]<heap[i+1]) //沿key较大的子节点的向下筛选,构建大根堆
{ //若if(i<len&&heap[i]>heap[i+1]);为构建小根堆
i++; //取key比较大的节点下标
}
if(heap[0]>=heap[i])break; //筛选结束(大根堆)
//若if(heap[0]<=heap[i])break; 为构建小根堆
else
{
heap[top]=heap[i]; //将heap[i]调整到双亲节点上
top=i;
}
}
heap[top]=heap[0];
}
//构建大根堆
void BuildMaxHeap(int heap[], int len)
{
for(int i=len/2; i>0; i--) //从i=[n/2]~1,反复调整堆
{
AdjustDown(heap, i, len);
}
}
//向上调整
void AdjustUp(int heap[], int key)
{
heap[0]=heap[key];
int i=key/2;
while(i>0&&heap[i]<heap[0])
{
heap[key]=heap[i];
key=i;
i=key/2;
}
heap[key]=heap[0];
}
//插入一个节点,并进行调整
void HeapInsert(int heap[], int &len, int key)
{
len++;
heap[len]=key;
AdjustUp(heap, len);
}
void ShowHeap(int heap[], int len)
{
for(int i=1; i<=len; i++)
{
cout << heap[i] << " ";
}
}
void Swap(int &a, int &b)
{
int t;
t=a;
a=b;
b=t;
}
//堆排序
void HeapSort(int heap[], int len)
{
BuildMaxHeap(heap, len);
for(int i=len; i>1; i--)
{
Swap(heap[i], heap[1]);
AdjustDown(heap, 1, i-1);
}
}
//删除第一个结点,并进行向下调整
int HeapDelete(int heap[], int &len)
{
int temp;
temp=heap[1];
heap[1]=heap[len];
len--;
AdjustDown(heap, 1, len);
return temp;
}
int main()
{
int heap[100];
int len;
cin >> len;
for(int i=1; i<=len; i++)
{
cin >> heap[i];
}
cout << "构建堆:";
BuildMaxHeap(heap, len);
ShowHeap(heap, len);
cout <<endl;
cout << "删除第一个结点:";
cout << HeapDelete(heap, len) << endl;
ShowHeap(heap, len);
cout << endl;
cout << "堆插入59:";
HeapInsert(heap, len, 59);
HeapSort(heap, len);
ShowHeap(heap, len);
cout << endl;
cout << "堆排序:";
HeapSort(heap, len);
ShowHeap(heap, len);
cout << endl;
cout << "删除第一个结点:";
cout << HeapDelete(heap, len) << endl;
ShowHeap(heap, len);
return 0;
}
//数据: 5 56 20 23 40 38 29 61 35 76 28 98
//大根堆:98 76 38 61 56 20 29 23 35 40 28 5
测试

更多推荐



所有评论(0)