数据结构:堆排序

简单介绍

堆排序就是利用堆这一数据结构来排序,堆使一颗完全二叉树,每个结点都不大于或者不小于他的儿子。关于排序的话,我们每次取出堆顶元素和堆尾的交换,然后由剩下的元素重新构建堆,最后我们将得到一个有序的序列。

Code

#include<bits/stdc++.h>
using namespace std;

void heap_adjust (int r[],int low,int high) {
	int i=low;
	int j=2*low+1;
	int temp=r[low];
	while (j<high) {
		if (j<high&&r[j]<r[j+1]) j++;  //每轮只需要对两个儿子进行操作,所以取大的操作比较一次就可以了
		if (temp<r[j]) {
			r[i]=r[j];
			i=j;
			j=2*i+1;   //调整位置继续构建堆
		}
		else break;
	}
	r[i]=temp;   //temp赋值给最后一个
	return ;
}

void heap_sort (int r[],int n) {
	int i;
	int temp;
	for (int i=n/2-1;i>=0;i--) heap_adjust (r,i,n-1); //最底层非叶子结点开始调整
	for (int i=n-1;i>=1;i--) {
		swap (r[0],r[i]);
		heap_adjust (r,0,i-1);   //此时下面均为有序,所以要从堆顶开始调整
	}
	return ;
}

int main () {
	int R[8]={49,38,65,97,76,13,27,49};
	heap_sort (R,8);
	for (int i=0;i<8;i++) printf ("%d ",R[i]);
	printf ("
");
	return 0;
}
原文地址:https://www.cnblogs.com/hhlya/p/14226951.html