[数据结构] 堆排序算法

#include <iostream>
#define MAX_SIZE 100
using namespace std;

typedef int keytype; 

typedef struct records          //排序类型 
{
	keytype key;
	//fields other; 
};

typedef records LIST[MAX_SIZE]; //排序数组

void Swap(records &x, records &y)
{
	records temp;
	temp = x;
	x = y;
	y = temp;
}

void PushDown(LIST list, int first, int last)
//整理堆,把list[first]中的数据推到堆中的适当位置 
{
	int r;
	r = first;
	while(r <= last/2)
	{
		if((r == last/2) && (last%2 == 0))
		//r有一个儿子,在2*r 
		{
		    if(list[r].key > list[2*r].key)
			  Swap(list[r], list[2*r]);
			r = last; 
		}
		else if((list[2*r].key < list[r].key) && (list[2*r].key <= list[2*r+1].key))
	    //将list[r]和左儿子交换 
	    {
		    Swap(list[r], list[2*r]);
		    r = 2*r; 
            }
	    else if((list[r].key > list[2*r+1].key) && (list[2*r+1].key < list[2*r].key))
	    //将list[r]和右儿子交换 
	    {
	        Swap(list[r], list[2*r+1]);	
	        r = 2*r+1;
	    }
	    else
	        r = last;
    }

}

void Sort(int n, LIST list)
//堆排序,将数组元素A[1],…,A[n]排成不增的序列 
{
   int i;
   for(i = n/2; i >= 1; i--)//初始建堆 
     PushDown(list, i, n);
   for(i = n; i >= 2; i--)
   {
       Swap(list[1], list[i]);//取出堆中最小元素 
       PushDown(list, 1, i-1);//整理堆 
   }
}

int main()
{
	LIST list;
	int i;
	
	cout << "Input the number of array:" << endl;
	cin >> list[0].key;
	for(i = 1; i <= list[0].key; i++)
	  cin >> list[i].key;
    
        Sort(list[0].key, list);
    
        for(i = 1; i <= list[0].key; i++)
	  cout << list[i].key;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值