c++学习连载-堆排序完整程序
来源:互联网 发布:好大夫网络问诊平台 编辑:程序博客网 时间:2024/06/05 20:30
#ifndef _HEAP_H_
#define _HEAP_H_
using namespace std;
class heap
{
public:
heap()
{
}
int HeapPar(int i)
{
return i/2;
}
int HeapLeft(int i)
{
return 2*i;
}
int HeapRight(int i)
{
return 2*i+1;
}
template <class T>
int getArrayLen(T& array)
{//使用模板定义一个函数getArrayLen,该函数将返回数组array的长度
return (sizeof(array) / sizeof(array[0]));
}
void InHeat(int A[]);
void MaxHeapify(int i);
void BuildMapHeap();
int* Pheap;
int HeapSize;
~heap()
{
}
};
#endif
#include"heap.h"
void heap::BuildMapHeap()
{
for(int i=heap::HeapSize/2;i>=1;i--)
{
heap::MaxHeapify(i);
}
}
#include"heap.h"
void heap::InHeat(int A[])
{
// HeapSize=getArrayLen(A);
Pheap=A;
}
#include"heap.h"
void heap::MaxHeapify(int i)
{
int l,r,largest;
int temp;
l=HeapLeft(i);
r=HeapRight(i);
if((l<=HeapSize)&&(Pheap[l-1]>Pheap[i-1]))
{
largest=l;
}
else
{
largest=i;
}
if((r<=HeapSize)&&(Pheap[r-1]>Pheap[largest-1]))
{
largest=r;
}
if(largest!=i)
{
temp=Pheap[i-1];
Pheap[i-1]=Pheap[largest-1];
Pheap[largest-1]=temp;
heap::MaxHeapify(largest);
}
}
#include"heap.h"
#include<iostream>
using namespace std;
void HeapSort(heap& B)
{
B.BuildMapHeap();
int i;
int int_tem;
for(i=B.HeapSize;i>=2;i--)
{
int_tem=B.Pheap[0];
B.Pheap[0]=B.Pheap[i-1];
B.Pheap[i-1]=int_tem;
B.HeapSize--;
B.MaxHeapify(1);
}
}
#include<iostream>
#include"heap.h"
#include"heapsort.h"
using namespace std;
int main()
{
int arry[]={5,13,2,25,7,17,20,8,4};
int i=0;
cout<<"the original array:"<<endl;
for(;i<9;i++)
{
cout<<arry[i]<<" ";
}
cout<<endl;
heap B;
B.InHeat(arry);
B.HeapSize=9;
HeapSort(B);
cout<<"the sorted arry:"<<endl;
for(i=0;i<9;i++)
{
cout<<B.Pheap[i]<<" ";
}
cout<<endl;
return 0;
}
程序测试结果:
- c++学习连载-堆排序完整程序
- c++学习连载-堆排序学习及遇到问题
- 选择排序法完整C程序
- 八大排序算法及完整c代码—堆排序c、java代码
- 堆排序的完整过程
- 二路归并排序算法实现-完整C语言程序
- 快速排序(完整程序c语言实现)
- C语言四种排序算法完整程序
- 算法导论第6章实现堆排序的完整程序
- C/C++学习之C提高----C程序数组排序、数据类型(大小,别名,封装)、变量、程序的内存四区模型(栈,堆,全局,代码区)
- 堆排序程序
- C语言程序----排序(直接插入排序,SHELL排序,冒泡排序,快速排序,简单选择排序,堆排序)
- 堆-堆排序学习总结
- 堆排序完整代码带详解
- 堆排序完整代码带详解(续)
- 堆排序----C语言
- 堆排序(C#)
- 堆排序C语言
- CDialog自绘
- ASP.NET Dictionary 的基本用法
- C陷阱与缺陷阅读笔记(下)
- sed直接替换文件内容
- Web中Readonly和Disabled的区别
- c++学习连载-堆排序完整程序
- COCOS2D-X在LINUX下的IDE
- shell脚本是防止多次运行
- Interface
- css样式截取过长省略号
- CListCtrl自绘
- Genesis-3D 入门教程—26.后处理五:景深效果
- linux c语言 select函数用法
- MYSQL Handler Socket插件(一)原理