标签:
// Heap.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
int h[101];//存放数组
int n;//存放数组元素个数
using namespace std;
//void swap(int *a,int *b)
//{
// int temp = *a;
// *a = *b;
// *b = temp;
//}
void swap2(int i,int j)
{
int temp = h[i];
h[i] = h[j];
h[j] = temp;
}
void shifdown(int i)//向下调整一般从1开始 99 5 36 7 22 17 92 12 2 19 25 28 1 46
{
int t;
int flag = 0;
while(2*i<=n && flag==0)
{
int ti = h[i];
if(h[i]>h[2*i]) //用t记录较小节点的编号
t=2*i;
else
t = i;
if(2*i+1 <=n)
{
if(h[t] > h[2*i+1])
t = 2*i+1;
}
if(t != i)
{
/*swap(h+t,h+i);*/
swap2(t,i);
i = t;
}
else
flag = 1;
}
}
int deletetop()
{
int t = h[1];
h[1] = h[n];
shifdown(1);
n--;
return t;
}
void create()
{
int i;
for(i=n/2;i>=1;i--)
{
shifdown(i);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int i,num;
cout<<"请输入元素个数:";
cin>>num;
for(i = 1;i <= num;i++)
cin>>h[i];
n = num;
create();
cout<<"堆排序后的二叉树:";
for(i = 1;i <= num;i++)
cout<<h[i]<<endl;
cout<<"堆排序后输出:";
for(i = 1;i <=num ;i++)
{
cout<<deletetop()<<endl;
}
system("pause");
return 0;
}
自己参照了别人的博客写的
标签:
原文地址:http://www.cnblogs.com/chdxiaoming/p/4632417.html