#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define LEN 20
typedef struct heapType
{
int *a;
int heapLen;
}heap,*heapPtr;
void swop(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
int partition(int a[],int p,int r)
{
int i=p-1,x=a[r],j;
for(j=p;j<r;j++)
{
if(a[j]>x)
{
i++;
swop(&a[j],&a[i]);
}
}
swop(&a[r],&a[i+1]);
return i+1;
}
int at(int a[],int p,int r,int i)
{
if(p==r)
return a[p];
int q=partition(a,p,r);
int k=q-p+1;
if(i==k)
return a[q];
else if(i<k)
return at(a,p,q-1,i);
else
return at(a,q+1,r,i-k);
}
void heapMaxify(heapPtr hp,int i)
{
int max=hp->a[i],maxi=i;
int l=hp->a[2*i],r=hp->a[2*i+1];
if(2*i<=hp->heapLen && l>max)
{
maxi=2*i;
max=l;
}
if(2*i+1<=hp->heapLen && r>max)
{
maxi=2*i+1;
max=r;
}
swop(&hp->a[i],&hp->a[maxi]);
if(maxi != i)
heapMaxify(hp,maxi);
}
heapPtr buildHeap(int a[],int len)
{
heapPtr hp=(heapPtr)malloc(sizeof(heap));
hp->a=a;
hp->heapLen=len;
for(int i=len/2;i>=1;i--)
{
heapMaxify(hp,i);
}
return hp;
}
int extractMax(heapPtr hp)
{
if(hp->heapLen<1)
return INT_MIN;
int r=hp->a[1];
hp->a[1]=hp->a[hp->heapLen];
hp->heapLen--;
heapMaxify(hp,1);
return r;
}
void heapSort(heapPtr hp)
{
}
void printA(int a[],int p,int r)
{
for(int i=p;i<=r;i++)
{
printf("%d ",a[i]);
}
printf("\n");
}
int main()
{
int a[10]={INT_MIN,98,23,2,11,6,24,76,84,55};
int k=5;
int max;
heapPtr hp=buildHeap(a,9);
/*at(a,1,9,k);//a.前k个最大的数
int index=partition(a,1,9);
printA(a,1,k);
for(int i=1;i<=k;i++)
{
max=extractMax(hp);
printf("%d ",max);
}//b.建立一个最大优先队列,并调用extract-max过程k次
printf("\n");*/
int *b=(int*)malloc((k+1)*sizeof(int));
b[0]=INT_MIN;
at(a,1,9,k);
for(int i=1;i<=k;i++)
{
max=extractMax(hp);
b[i]=max;
}//c.利用顺序统计量算法找第k大元素,再对前i大的数排序
printA(b,1,k);
getchar();
}
算法导论 思考题 9-1
最新推荐文章于 2021-07-08 20:29:31 发布