堆排序

#include <iostream>
using namespace std;

int parent(int i)
{
return i/2;
}

int left(int i)
{
return 2*i;
}

int right(int i)
{
return 2*i+1;
}

void exchange(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}

void max_heapify(int *a,int i,int heap_size)
{
int l=left(i);
int r=right(i);
int largest;
if (l<=heap_size&&a[l]>a[i])
{
largest=l;
}
else
{
largest=i;
}
if (r<=heap_size&&a[r]>a[largest])
{
largest=r;
}
if (largest!=i)
{
exchange(a[i],a[largest]);
max_heapify(a,largest,heap_size);
}

}

void build_max_heap(int *a,int heap_size)
{
for (int i=heap_size/2;i>=0;i--)
{
max_heapify(a,i,heap_size);
}
}

void heapsort(int *a,int heap_size)
{
build_max_heap(a,heap_size);
int length;
length=heap_size;
for (int i=length;i>=1;i--)
{
exchange(a[0],a[i]);
heap_size=heap_size-1;
max_heapify(a,0,heap_size);
}
}

int main()
{
int a[]={4,1,3,2,16,9,10,14,8,7,3,2,45,7,86,4,3,2,1};
int heap_size=sizeof(a)/sizeof(int)-1;
heapsort(a,heap_size);

for (int i=0;i<=heap_size;i++)
{
cout<<a[i]<<"";
}
cout<<endl;
system("pause");
return 0;

}

转载于:https://www.cnblogs.com/tiandsp/archive/2012/02/17/2356260.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值