哈夫曼树的创建以及冒泡排序法的应…

#include <iostream>//
using namespace std;
typedef struct  
{
int weight;
int parent;
int Lchild;
int Rchild;
}Node;
//creat the Huffman tree
Node* Creat(Node node[],int n)//n is the total leaves,then 2n-1 is the total nodes
{
for (int k=0;k<2*n -1;k++)
{
if (k<n)
{
printf("please input every weight\n");
scanf("%d",&node[k].weight);
}
else
{
// isn't leaf
node[k].weight=0;
}
node[k].parent=node[k].Lchild=node[k].Rchild=0;
}
for (int l=n;l <2*n-1;l++)
{
int min1=32767;
int min2=32767;//store the two min value
int p1=0;
int p2=0;//store the index
for (int j=0;j<=l-1;j++)
{
if (node[j].parent==0)
{
if (node[j].weight<min1)
{
min2=min1;
p2=p1;
p1=j;
min1=node[j].weight;
}
else if (node[j].weight<min2)
{
min2=node[j].weight;
p2=j;
}
}
}
//please ensure the code's position
node[l ].Lchild=p1;
node[l].Rchild=p2;
node[l].weight=min1+min2;
node[p1].parent=l;;
node[p2].parent=l;
}
return node;
}
Node *Order(Node node1[],int n)
{
//bubbling way 
int flag;
int temp;
for (int i=0;i<n-1;i++)
{
flag=1;
for (int j=0;j<n-i-1;j++)
{
if (node1[j].weight>node1[j+1].weight)
{
temp=node1[j].weight;
node1[j].weight=node1[j+1].weight;
node1[j+1].weight=temp;
flag=0;
}
}
if (flag==1)
{
printf("the order is completed in the times of ");
printf("%d",i );//the order is completed
cout<<endl;
break;
}
}
return node1;
}
int main()
{
//cout<<"please input Huffman's leaves"<<endl;
cout<<"please input the number of leaves"<<endl;
int number;
cin>>number;
Node *node=new Node[2*number  -1];//http://tieba.baidu.com/p/1746294833
node =Creat(node,number);
node=Order(node,2*number-1);
cout<<"the following is the result"<<endl;
cout<<"from the bottom to the top ,and from the left to the right"<<endl;
for (int l=0;l<2*number-1;l++)
{
cout<<node[l].weight<<endl;
}
delete [] node;
return 0;
}//////////////////////////////////////////////////////////////////////////

你可能感兴趣的:(哈夫曼树的创建以及冒泡排序法的应…)