Analyzing the course,There are 2 points must to be take care:
1 : max_heapify() cost O(lgn) time,build_heap cost O(n).so we can say that the total runing time is
O(nlgn). But is not a tight bound. CLRS says that we can done it in linear time.
2: n-element heap,the leaps nodes is [n/2]+1,[n/2]+2....n
3: still question 6.3-3
#include<stdio.h>
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
void max_heapify(int a[],int i,int a_size)
{
int l=2*i+1;
int r=2*i+2;
int largest;
if(l<=(a_size-1)&&a[i]<a[l])
largest=l;
else
largest=i;
if(r<=(a_size-1)&&a[largest]<a[r])
largest=r;
if(largest!=i){
swap(&a[i],&a[largest]);
max_heapify(a,largest,a_size);
}
}
void build_maxheap(int a[],int size)
{
int i=(size-1)/2;
for(;i>-1;i--){
max_heapify(a,i,size);
}
}
int main()
{
int a[]={3,2,4,5,6,76,87,78,9};
build_maxheap(a,9);
int i;
for(i=0;i<8;i++)
printf("%d ",a[i]);
printf("/n");
return 0;
}
1 : max_heapify() cost O(lgn) time,build_heap cost O(n).so we can say that the total runing time is
O(nlgn). But is not a tight bound. CLRS says that we can done it in linear time.
2: n-element heap,the leaps nodes is [n/2]+1,[n/2]+2....n
3: still question 6.3-3
#include<stdio.h>
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
void max_heapify(int a[],int i,int a_size)
{
int l=2*i+1;
int r=2*i+2;
int largest;
if(l<=(a_size-1)&&a[i]<a[l])
largest=l;
else
largest=i;
if(r<=(a_size-1)&&a[largest]<a[r])
largest=r;
if(largest!=i){
swap(&a[i],&a[largest]);
max_heapify(a,largest,a_size);
}
}
void build_maxheap(int a[],int size)
{
int i=(size-1)/2;
for(;i>-1;i--){
max_heapify(a,i,size);
}
}
int main()
{
int a[]={3,2,4,5,6,76,87,78,9};
build_maxheap(a,9);
int i;
for(i=0;i<8;i++)
printf("%d ",a[i]);
printf("/n");
return 0;
}