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;
}


posted on 2011-07-29 15:56  more think, more gains  阅读(231)  评论(0编辑  收藏  举报

导航