堆排序(1)

本文探讨了堆排序中最大堆调整算法max_heapify的时间复杂度为O(log n),并指出通过优化可以实现线性时间构建最大堆。此外,还提供了一个具体的C语言实现案例,包括max_heapify函数和build_maxheap函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值