(日志,《算法导论》.6.2)堆排序,代码
来源:互联网 发布:长春典恒网络百度贴吧 编辑:程序博客网 时间:2024/06/03 10:23
堆形式:MAX-HEAPIFY
测试代码如下:
<pre name="code" class="cpp">/***********************************************************************************程序名称 :heapsort_test功能描述 : 堆排序,递归 修改历史 : 1.日 期 : 2015/10/5作 者 : gqkly内容 : ************************************************************************************/#include <iostream>#include <string>#include <time.h>#include <stdio.h>using namespace std;typedef int ElemType;#define InitHeap(heap,len) { memset(&heap,0,sizeof(heap));heap.length=len;}#define InitHeapA(heap) {heap.A=(ElemType*)malloc(heap.length*sizeof(ElemType));for(int i=0;i<heap.length;i++)heap.A[i]=rand()%50;}#define Right_Of_I(i) (2*i+1)#define Left_Of_I(i) (2*i)#define swap1(a,b) {a=a+b;b=a-b;a=a-b;}#define swap2(a,b) {a=a+b-(b=a);}#define swap3(a,b) {b=a+(a=b)*0;}#define swap4(a,b) {a=a^b;b=a^b;a=a^b;}#define N 10typedef struct HEAP_TYPE{ElemType *A;int length;}HEAP,*HEAP_PTR;void Max_Heapify(HEAP* heap,int i);//中间层和第三层void Build_Max_Heap(HEAP* heap);//中间层void Heap_Sort(HEAP* heap);//第一层函数void Print_Heap(HEAP heap,char *string);int main(){HEAP heap_a;InitHeap(heap_a,N);InitHeapA(heap_a);Print_Heap(heap_a,"start:");Heap_Sort(&heap_a);Print_Heap(heap_a,"MAX-HEAPIFY:");getchar();return 0;}void Max_Heapify(HEAP* heap,int i)//这个参数i为数学位置,函数内部转化为数组坐标{int largest;int l=Left_Of_I(i);int r=Right_Of_I(i);if ( (l<=(*heap).length) && ((*heap).A[l-1])>((*heap).A[i-1]) ){largest=l;}else largest=i;if ( (r<=(*heap).length) && ((*heap).A[r-1])>((*heap).A[largest-1]) ){largest=r;}if (largest!=i){swap1( (*heap).A[i-1],(*heap).A[largest-1] );Max_Heapify(heap,largest);}}void Build_Max_Heap(HEAP* heap){int len=(*heap).length;for (int i=(len/2);i>0;i--){Max_Heapify(heap,i);}}void Heap_Sort(HEAP* heap){int tmp_size=(*heap).length;Build_Max_Heap(heap);for (int i=(*heap).length-1;i>0;i--)//长度的大小和坐标不一样{swap1((*heap).A[0],(*heap).A[i]);(*heap).length--;//此处通过减小堆大小来为排序服务,所以需要在之后还原Max_Heapify(heap,1);//1是数学位置--第一个元素}(*heap).length=tmp_size;//还原堆大小}void Print_Heap(HEAP heap,char *string){int tmp=0;int t=2;cout<<"***********************************************"<<endl;cout<<string<<endl;for (int i=0;i<heap.length;i++){tmp=i+1;if ((i+1)==t){t*=2;tmp=i+1;cout<<endl;}cout<<heap.A[i]<<' ';}cout<<endl;}
运行:
0 0
- (日志,《算法导论》.6.2)堆排序,代码
- (日志,《算法导论》.6.4)优先队列,堆,代码
- 堆排序(算法导论)
- 堆排序(算法导论)
- 堆排序(依据算法导论伪代码)
- 《算法导论》第六章-堆排序(伪代码)
- 《算法导论》代码搬运工--堆排序
- 堆排序(最小堆)--【算法导论】
- (日志,《算法导论》.7)快速排序,代码
- (日志,《算法导论》.8.2)计数排序,代码
- 【算法导论】排序 (二):堆排序
- 算法导论 堆排序
- 算法导论--堆排序
- 【算法导论】 堆排序
- 算法导论-----堆排序
- 【算法导论】堆排序
- 算法导论-堆排序
- 堆排序--算法导论
- C语言编译全过程
- 设置git bash可以用鼠标编辑
- 文件上传类
- HDU 5317(打表)
- raspberry pi 2安装n2n,穿透长城宽带的内网映射限制
- (日志,《算法导论》.6.2)堆排序,代码
- iOS XIB以及Storyboard的部分使用方法
- 华为oj_找出字符串中第一个只出现一次的字符
- git error: unable to unlink old (Permission denied)
- 国外程序员推荐:每个程序员都应读的书
- C代码实现数组
- LeanCloud获取最近会话列表和获取最后一条聊天记录
- Incompatible pointer types returning 'NSArray *' from a function with result type 'xxx *'
- 编程书籍推荐_3