堆排序

/*
堆排序
VS2010
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

#define OK 1
#define TRUE 1
#define FALSE 0
#define MAXSIZE 50

typedef struct
{
	int value;
	int index;
}RedType;

typedef struct
{
	RedType red[MAXSIZE+1];	//red[0]用作哨兵单元
	int length;
}HeapList;

HeapList *CreateHeap()
{
	int i = 0;
	int j = 0;
	char buf[4*MAXSIZE] = "";
	char *ptr = NULL;
	HeapList *heaplist = (HeapList *)malloc(sizeof(HeapList));
	memset(heaplist, 0, sizeof(HeapList));

	printf("请输入待排序数据,以逗号分隔,以分号结束\n"
		"例:23,12,65,36,35;\n"
		"input:");
	scanf("%s", buf);

	ptr = buf;
	heaplist->red[i].value = 0;	//red[0]不存值用作哨兵单元
	i = 1;
	while(*ptr != ';')
	{
		heaplist->red[i].value = atoi(ptr);
		heaplist->red[i].index = i;
		i++;

		ptr = strstr(ptr, ",");
		if(!ptr)
		{
			break;
		}
		ptr++;
	}
	heaplist->length = (i - 1);

	return heaplist;
}

int HeapAdjust(HeapList *heaplist, int start, int end)
{
	int i = 0;
	heaplist->red[0] = heaplist->red[start];
	for(i = 2 * start; i <= end; i = i * 2) /*沿关键字较大的孩子结点向下筛选*/
	{
		if((i < end) && (heaplist->red[i].value < heaplist->red[i+1].value))
		{
			i++;		//i为当前节点(start节点)的子节点中较大的那一个
		}
		if(heaplist->red[0].value < heaplist->red[i].value)
		{
			heaplist->red[start] = heaplist->red[i];
			start = i;
		}
	}
	heaplist->red[start] = heaplist->red[0];
	
	return OK;
}

//对顺序表进行堆排序
int HeapSort(HeapList *heaplist)
{
	int i = 0;
	for(i = (heaplist->length / 2); i > 0; i--)		//将heaplist构建成大顶堆
	{
		HeapAdjust(heaplist, i, heaplist->length);
	}

	for(i = heaplist->length; i > 1; i--)
	{
		//将堆顶记录和当前未排序的最后一个记录交换
		heaplist->red[0] = heaplist->red[1];
		heaplist->red[1] = heaplist->red[i];
		heaplist->red[i] = heaplist->red[0];

		HeapAdjust(heaplist, 1, i-1);	//将heaplist->red[1..i-1]重新调整为大顶堆
	}

	return OK;
}

//打印堆中数据
int PrintHeapType(HeapList heaplist)
{
	int i = 0;
	for(i = 1; i <= heaplist.length; i++)
	{
//		printf("(%d,%d),", heaplist.red[i].index, heaplist.red[i].value);
		printf("%d,", heaplist.red[i].value);
	}
	printf("\b;\n");
	return OK;
}

int main()
{
	HeapList *heaplist = NULL;
	HeapList *testheaplist = NULL;
	heaplist = CreateHeap();
	testheaplist = (HeapList *)malloc(sizeof(HeapList));

	printf("\n堆排序:\n");
	memcpy(testheaplist, heaplist, sizeof(HeapList));
	PrintHeapType(*testheaplist);
 	HeapSort(testheaplist);
 	PrintHeapType(*testheaplist);

	free(testheaplist);
	free(heaplist);
	system("pause");
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值