heap sort demo

本文介绍了一个简单的堆操作演示程序,包括插入、删除最小元素及获取堆顶元素等功能。该程序使用 C 语言编写,通过命令行界面进行交互,支持用户输入指令来执行堆的基本操作。
/*
 * heap_demo.c
 * mike-w
 * 2012-7-23
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>

#define HEAP_SIZE (2<<13)
#define BUF_SIZE 256

int swap(int *e1, int *e2)
{
	int tmp=*e1;
	*e1=*e2;
	*e2=tmp;
	return 0;
}

int heap_in(int *heap, int e)
{
	if(heap[0]==HEAP_SIZE)
	{
		puts("heap is full :-(");
		return -1;
	}
	heap[++heap[0]]=e;
	int c=heap[0], p=c/2;
	while(p>0 && heap[p]>heap[c])
		swap(heap+p, heap+c), c=p,p=c/2;
	return 0;
}

int heap_out(int *heap, int *e)
{
	if(!heap[0])
	{
		puts("heap is empty :-(");
		return -1;
	}
	*e=heap[1];
	swap(heap+1,heap+heap[0]);
	heap[0]--;
	int p=1, lc, rc, x;
	while(1)
	{
		x=p;
		lc=2*p;
		rc=2*p+1;
		if(lc<=heap[0] && heap[lc]<heap[x])
			x=lc;
		if(rc<=heap[0] && heap[rc]<heap[x])
			x=rc;
		if(x!=p)
			swap(heap+x, heap+p), p=x;
		else
			break;
	}
	return 0;
}

int get_top(int *heap,int *e)
{
	if(!heap[0])
	{
		puts("heap is empty :-(");
		return -1;
	}
	else
	{
		*e=heap[1];
		return 0;
	}
}

void good_bye(void)
{
	puts("good bye :-)");
	return;
}

int help(void)
{
	puts("instructions:");
	puts("insert [number]: insert number into the heap");
	puts("pop: \t\tpop out a number from the heap");
	puts("get_top: \tdisplay the number at the top of the heap");
	puts("help: \t\tdisplay this message");
	puts("quit: \t\tquit");
	return 0;
}

int get_command(int *p)
{
	char buf[BUF_SIZE];
	printf("=>");
	scanf("%s",buf);
	if(!strcmp(buf,"insert"))
	{
		scanf("%d",p);
		return 1;
	}
	else if(!strcmp(buf,"pop"))
		return 2;
	else if(!strcmp(buf,"get_top"))
		return 3;
	else if(!strcmp(buf,"help"))
		return 4;
	else if(!strcmp(buf,"quit"))
		return 5;
	else
		return -1;
}

int main(void)
{
	int p1,cmd;

	atexit(good_bye);
	
	int heap[HEAP_SIZE],e;
	memset(heap,0,sizeof(heap));

	/* welcome msg */
	puts("*****************************");
	puts("*      heap demo v1.0       *");
	puts("*      author: mike-w       *");
	puts("*         2012-7-23         *");
	puts("*****************************");
	help();
	
	while((cmd=get_command(&p1)))
	{
		switch(cmd)
		{
			case 1: /* insert */
				if(!heap_in(heap, p1))
					printf("%d is inserted into the heap\n", p1);
				break;
			case 2: /* pop */
				if(!heap_out(heap,&e))
					printf("%d is popped out from the heap\n",e);
				break;
			case 3: /* get_top */
				if(!get_top(heap, &e))
					printf("%d is at the top of the heap\n",e);
				break;
			case 4: /* help */
				help();
				break;
			case 5: /* quit */
				exit(0);
				break;
			default:
				puts("invalid command ==!");
		}
	}
	return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值