堆排序

/*
堆排序
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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章