码迷,mamicode.com
首页 > 编程语言 > 详细

堆排序

时间:2015-07-09 11:01:43      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

// 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!