堆排序 代码(加注释)

#include <iostream>
#include <cstring>
#include <algorithm> 
using namespace std;
void HeapAdjust(int *a, int i, int size){
	int lchild = 2*i; 
	int rchild = 2*i + 1;
	int max = i;
	if(i<=size/2){
		if(lchild<=size && a[lchild] > a[max]){
			max = lchild;
		}
		if(rchild<=size && a[rchild] > a[max]){
			max = rchild;
		}
		if(max!=i){
			swap(a[i], a[max]);
			HeapAdjust(a, max, size);   //当节点的值有一点变化,相应的孩子节点也要重新调整,维护堆的特性; 
		}
	}
}
void BuildHeap(int *a, int size){	
	for(int i=size/2; i>=1; --i){	//这里是为了使每一个节点,保持堆的特性;(节点大于孩子节点) 
		HeapAdjust(a, i, size);
	}
}
void heapSort(int a[],int size){	
	BuildHeap(a, size);			//建立一个大顶堆, 根节点值最大, 
	for(int i=size; i>=1; --i){
		swap(a[1], a[i]);		//然后,与最后一个元素的值交换 ;保证了最后一个元素最大; 
		HeapAdjust(a, 1, i-1);	//除了最后一元素的值,其它元素重新调整; 
	}
}
int main() {
	int a[7] = {9, 5, 6, 7, 8, 9, 1};
	heapSort(a, 6);
	for(int i=0; i<7; ++i){
		printf("%4d", a[i]);
	}
	return 0;
}

发布了76 篇原创文章 · 获赞 0 · 访问量 7198

猜你喜欢

转载自blog.csdn.net/julicliy/article/details/79332245
今日推荐