《数据结构与算法分析》习题6.2,这题是问答题,心血来潮下决心用程序实现,编程菜鸟前前后后调试了大概一天时间才完成两种算法,下面是第一种算法,时间复杂度为O(NlogN)。
#include<stdio.h>
#include<stdlib.h>
typedef struct heapStruct
{
int Capacity;
int Size;
int *Elements;
}*priorityQueue;
priorityQueue initQueue(int n)
{
priorityQueue H;
H = (priorityQueue)malloc(sizeof(priorityQueue));
if(H == NULL)
printf("Out of space!!!");
H->Elements = (int *)malloc((n+1)*sizeof(int));
if(H->Elements == NULL)
printf("Out of space!!!");
H->Capacity = n;
H->Size = 0;
H->Elements[0] = -1;
return H;
}
int isFull(priorityQueue H)
{
return H->Size == H->Capacity;
}
int isEmpty(priorityQueue H)
{
return H->Size == 0;
}
void Insert(int X, priorityQueue H)
{
int i;
if(isFull(H))
{
printf("Priority queue is full");
return;
}
for(i = ++H->Size; H->Elements[i/2] > X; i /= 2)
H->Elements[i] = H->Elements[i/2];
H->Elements[i] = X;
}
void printQueue(priorityQueue H)
{
int i;
if(isEmpty(H))
printf("H is NULL");
for(i=1; i<=H->Size; i++)
printf("%d ", H->Elements[i]);
}
void main()
{
int input[15] = {10,12,1,14,6,5,8,15,3,9,7,4,11,13,2};
int i;
priorityQueue H = initQueue(20);
for(i = 0; i < 15; i++)
Insert(input[i], H);
printQueue(H);
}
第二种算法是将N个关键字以任意顺序放入书中,保持结构特性。为了保持二叉堆的性质可能需要将父节点下滤,时间复杂度为O(N)。使用Swap函数的时候遇到问题,后面将会总结一下Swap函数。
#include<stdio.h>
#include<stdlib.h>
typedef struct heapStruct
{
int Capacity;
int Size;
int *Elements;
}*priorityQueue;
int isFull(priorityQueue H)
{
return H->Size == H->Capacity;
}
int isEmpty(priorityQueue H)
{
return H->Size == 0;
}
void Swap(int *a, int *b)
{
int Tmp = *a;
*a = *b;
*b = Tmp;
}
void percolateDown(int i, priorityQueue H)
{
int j;
for(j=i; (2*j+1) <= H->Size && H->Elements[j]>Min(H->Elements[2*j],H->Elements[2*j+1]);)
{
if(H->Elements[2*j]<H->Elements[2*j+1])
{
Swap(&H->Elements[j], &H->Elements[2*j]);
j *= 2;
}
else
{
Swap(&H->Elements[j], &H->Elements[2*j+1]);
j = 2*j+1;
}
}
}
priorityQueue buildHeap(int a[], int n)
{
int i, j;
priorityQueue H;
H = (priorityQueue)malloc(sizeof(priorityQueue));
if(H == NULL)
printf("Out of space!!!");
H->Elements = (int *)malloc((n+1)*sizeof(int));
if(H->Elements == NULL)
printf("Out of space!!!");
H->Capacity = n;
H->Size = n;
H->Elements[0] = -1;
for(i=1; i<=n; i++)
H->Elements[i] = a[i-1];
for(j=n/2; j>0; j--)
percolateDown(j, H);
return H;
}
int Min(int a, int b)
{
return ((a < b)? a : b);
}
void printQueue(priorityQueue H)
{
int i;
if(isEmpty(H))
printf("H is NULL");
for(i=1; i<=H->Size; i++)
printf("%d ", H->Elements[i]);
}
void main()
{
int input[15] = {10,12,1,14,6,5,8,15,3,9,7,4,11,13,2};
printQueue(buildHeap(input, 15));
}