算法与数据结构之堆排序

一,线性的数组可以看成一个二差堆,堆中父节点与左孩子的关键码关系为:left=parent*2+1;

堆排序思想:每次循环从二叉堆中将最大的元素shiftup上移至根节点,再将根节点与最后对末尾的元素交换。撇开末尾元素,如此再继续找出下一个最大元素,将此最大元素与此末尾元素交换。依此重复查找最大元素,然后交换。

1.堆排序与插入排序思想有点类似。

2.时间复杂度为nlog2(n);

int heap[]={53,17,78,9,45,65,87,23};
void swap(int *a,int *b){
	int temp=*a;
	*a=*b;
	*b=temp;
}

void getMax(int cus,int end){
	while(cus>=0){
		int left=cus*2+1;
	int max=left;
	if(max<end&&heap[left]<heap[left+1])
		max++;
	if(heap[max]>heap[cus])
		swap(&heap[max],&heap[cus]);
	cus--;
	}
}
void heapSort(const int s){
	int size=s,current;
	while(size>1){
		current=(size-2)/2;
	getMax(current,size-1);
	swap(&heap[0],&heap[size-1]);
	size--;
	}
}

int main(){
  //  minHeap(8);
	show();
	heapSort(8);
	show();
	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值