heap 堆的各类操作

#include <stdio.h>
#include
<string.h>
#include
<stdlib.h>

int N;
//最小堆
int heap[20];

//交换两个元素的值

void swap( int &x, int &y)
{
int temp;
temp
= x;
x
= y;
y
= temp;
}

// 非递归写法
void down ( int x )
{
int i, j, flag = 1;
if ( 2 * x <= N) {
while (flag && (i = 2 * x) <= N )
{
if ( i + 1 <= N && heap[i] > heap[i+ 1] )
i
++;
if ( heap[x] > heap[i])
swap(heap[x],heap[i]), x
= i;
else
flag
= 0;
}

}
}

// 递归写法

void down_x ( int x)
{
int i = 2 * x;
if ( i <= N ) {
if ( i + 1 <= N && heap[i] > heap[i+1])
i
++;
if (heap[x] > heap[i]) {
swap(heap[x],heap[i]);
down(i);
}
}
}

//上移,非递归
void up( int x )
{
int flag = 1;
while ( x > 1 && flag )
{
if ( heap[x] < heap[x / 2]) {
swap(heap[x],heap[x
/ 2]);
x
= x / 2;
}
else
flag
= 0;
}

}


//上移,递归
void up_x( int x)
{
if (x > 1 && heap[x] < heap[x/2]) {
swap(heap[x],heap[x
/2]);
up( x
/ 2);
}
}

//建堆
void makeheap(int x)
{
int i;
for(i = x / 2; i; i--)
down_x(i);
}

//从小到大输出
void heap_sort( )
{
int i;
for ( i = N; i; i--) {
printf(
"%d ",heap[1]);
swap(heap[i], heap[
1]);
N
--;
down_x(
1);
}
}

int pop( )
{
swap(heap[
1],heap[N--]);
down(
1);
return heap[N + 1];
}

int main( )
{
int i, j;
scanf(
"%d",&N);
j
= N;
for (i = 1; i <= N; i++) {
scanf(
"%d",&heap[i]);
up(i);
}
//makeheap(N);
//heap_sort( );
for (i = 0; i < j; i++)
printf(
"%d ",pop( ));
return 0;
}


转载于:https://www.cnblogs.com/tangcong/archive/2011/07/29/2121135.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值