手写堆排序

//选择排序之堆排序
#include<stdio.h>
#include<malloc.h> 

//malloc可以使用sizeof 
int swap(int a[],int i,int j)//交换数组里两个元素 顺序 
{int temp=a[j];
a[j]=a[i];
a[i]=temp;
return 0;
}

int display(int a[],int len)//打印数组 
{
	for(int i=0;i<len;i++)
	printf("%d ",a[i]);//数组元素之间有空格 
	printf("\n") ;
	return 0;
}
int adjustheap(int a[],int node,int len){//调整某个节点使其和其子树形成大根堆 
	int right,left,max;
	right=node*2+1;
	left=node*2+2;
	max=node;
	
		if( left < len && a[left] > a[max])
                max = left;
        if( right < len && a[right] > a[max])
                max = right;
        if(max != node)
        {
                swap( a,max,node);
                adjustheap(a, max, len);
        }
		return 0;
	}
	
	
int makeheap(int a[],int len){//建堆 
	for(int i=len/2-1;i>=0;i--)
	adjustheap(a,i,len);
	return 0;
}
int heapsort(int a[],int len){//将堆从小到大排序 
	makeheap(a,len);
	for(int j=len-1;j>=0;j--){

	swap(a,0,j);
		adjustheap(a,0,j);	
	}
	
	return 0;
}
int main(){
	int a[]={3,5,2,5,78,999,1,-3};//这里给定了数组,可以尝试换成随机数组 
	int n=sizeof(a)/sizeof(a[0]) ;
	printf("排序前的数组\n");
	display(a,n);
	heapsort(a,n);
	printf("排序后的数组\n"); 
	display(a,n);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值