/*
堆排序
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;
}
堆排序
最新推荐文章于 2024-09-04 23:05:17 发布