算法导论chapter代码实现

根据书上的伪代码实现的最大堆,以及在最大堆基础上实现的优先级队列:

#include<iostream>
#include <time.h>
#include <limits.h>
using namespace std;
int n=11;
int a[100]={-1};
void print(int *a,int n)
{
    for(int i = 0; i < n; ++i)
        cout << a[i] << " ";
    cout << endl;
}
void inline my_swap(int &a,int &b)
{
    int temp = a;
    a = b;
    b = temp;
}
void max_heapify(int *a,int i,int n)
{
    int l = 2*i+1,r = l + 1, largest = i;
    if(l < n && a[l] > a[i])
        largest = l;
    if(r < n && a[r] > a[l])
        largest = r;
    if(largest != i)
    {
        my_swap(a[largest],a[i]);
        max_heapify(a,largest,n);
    }
}
void build_max_heap(int *a,int n)
{
    for(int i = n/2; i >= 0; --i)
       max_heapify(a,i,n);
}
void heapsort(int *a,int n)
{
    build_max_heap(a,n);
    cout<<"建立最大堆之后: ";
    print(a,n);
    int size=n;
    for(int i = n-1; i > 0; --i)
    {
        my_swap(a[0],a[i]);
        --size;
        max_heapify(a,0,size);
    }
}
//返回最大堆的最大值
int heap_max(int *a)
{
	return a[0];
}
//返回最大值同时删除此最大值病保持最大堆状态
int heap_extract_max(int *a)
{
	if(n<1)
		 cerr<<"heap underflow"<<endl;
	int max=a[0];
	a[0]=a[n-1];
	--n;
	build_max_heap(a,n);
	return max;
}
//增加某个节点的值并保持最大堆状态
void heap_increase_key(int *a,int i,int key)
{
	if(i>=n)
		throw string("i is too big\n");
	if(key<a[i])
		throw string("key is not valid"); 
	a[i]=key;
	int j=i%2==0?(i/2-1):i/2;
	while(i>0 && a[j]<a[i])
	{
		my_swap(a[i],a[j]);
		i=j;
	    j=i%2==0?(i/2-1):i/2;
	}
}
void max_heap_insert(int *a,int key)
{
    n++;
	a[n-1]=INT_MIN;
	heap_increase_key(a,n-1,key);
}
int main()
{
    srand(time(NULL));
    for(int i=0;i<n;++i)
        a[i]=i;
    cout<<"建立最大堆之前:\n";
    print(a,n);
    cout<<"最大堆排序之后:\n";
	build_max_heap(a,n);
    print(a,n);
	cout<<"heap_max is "<<heap_max(a)<<endl;
	cout<<"heap_max is "<<heap_extract_max(a)<<endl;
	cout<<"after extract_max the heap turns to:\n";
	print(a,n-1);
	heap_increase_key(a,3,100);
	cout<<"after increase a["<<3<<"] to "<<100<<" is \n";
	print(a,n);
	cout<<"after insert a new num into the max_heap:\n";
	max_heap_insert(a,11);
	print(a,n);
}

在VS2010上的运行结果:

posted @ 2010-11-05 15:04  hailong  阅读(270)  评论(0编辑  收藏  举报