第六章 堆排序 C++

来源:互联网 发布:部落冲突箭塔升级数据 编辑:程序博客网 时间:2024/05/20 04:28

二叉堆:是一个数组,可以看成一个近似的完全二叉树。除了最低层,该树是完全满的。有两种形式:最大堆和最小堆。

堆的两个用途:排序和优先队列。

排序:若要按升序排列,则使用最大堆。

有限队列:在计算机作业调度中一般使用最大堆,在基于事件驱动的模拟器中使用最小堆。


堆的常用操作为:

MAX_HEAPIFY (A,i)  此操作用来维护堆的性质。

BUILD-HEAP(A)  次操作用来把一个数组转为最大堆。

堆排序算法:

HEAPSORT(A)

BUILD-HEAP(A)  

for i = A.length dowto 2

swap A[1]  with  A[i]

A.heapsize  = A.heapsize - 1

MAXHEAPIFY(A,i)


书上的练习题6.1.1  到 6.3.3  使用了堆的很多性质,有时间可以在做一下,有助于对堆的深入理解。

下面附上源代码和结果图:

#include <iostream>using namespace std;static const int maxeles = 1024;void MaxHeapify(int *array,int ith,int len){while(true){int left = ith << 1;int right = (ith << 1) + 1;int largest;if(left < len && array[left] > array[ith])largest = left;else largest = ith;if(right < len && array[right] > array[largest])largest = right;if(largest != ith){int tmp = array[largest];array[largest] = array[ith];array[ith] = tmp;ith = largest;}else{return;} }}void BuildMaxHeap(int *array,int len){for(int i = (len >> 1);i >= 0;--i)MaxHeapify(array,i,len);return ;}int main(int argc,char **argv){int array[maxeles];int i = 0;while(cin >> array[i] && i < maxeles)++i;cout << "the original data is ";for(int j = 0;j < i;++j){cout << array[j] << ' ';}cout << endl;cout << "the MaxHeap data is ";BuildMaxHeap(array,i);for(int j = 0;j < i;++j){cout << array[j] << ' ';}cout << endl;int tmp;int len = i;for(int j = i - 1;j > 0;--j){tmp = array[0];array[0] = array[j];array[j] = tmp;len -= 1;MaxHeapify(array,0,len);}cout << "the MaxHeapSort data is ";for(int j = 0;j < i;++j){cout << array[j] << ' ';}cout << endl;return (0);}



0 0
原创粉丝点击