算法之排序-----排序第四篇 堆排序
来源:互联网 发布:linux idea 安装 编辑:程序博客网 时间:2024/05/21 14:07
堆排序
- 真言
头会疼,但是总有停止的那一刻,抓住那一刻去总结。否则头白疼啦。
- 引言
堆排序算法在大量数据排序中还是比较实用的,现在有好几个排序算法啦,有什么优缺点,也可以总结了。
- 思路
堆排序的算法就是两步建堆和维护。建堆一次,维护堆 n-2 次(第一次维护的时候 堆规模为 n-1,最后一次维护的时候堆规模为 2)。举个例子吧,我喜欢图,我相信你们也喜欢。一共有10个数据,如下建堆过程中如下数据如下变化建堆完毕。交换数据,堆规模建减小,维护堆,直至堆规模为 1.过程如下第一次第二次第三次第四次第五次第六次第七次第八次最后成为
- 实验
- 代码
test.cpp// choice sort #include<iostream>#include<Windows.h>#include<ctime>using namespace std;// use 1000,00 to test int const size = 1000000;// template function declaretemplate<class T> void Heap_sort(T *data,const int length);// template function template<class T> void Make_heap(T *data,const int length);// template function template<class T> void Heap_downcast(T *data,int i,const int length);int main(){DWORD S,E;int * data = new int[size];for(int i =0 ; i<size; i++){data[i] = rand();}cout<<"data initialize over"<<endl;S = GetTickCount();Heap_sort(data,size);E = GetTickCount();//for(int i =0 ; i<size; i++)//{//cout<<data[i]<<endl;//}cout<<endl<<"给"<<size<<"个数据选择排序,费时"<<E-S<<"毫秒"<<endl;system("pause");return 0;}// template function template<class T> void Heap_sort(T *data,const int length){if(data != NULL && length >= 0){Make_heap(data,length);T d;int L = length;while(L>1){d=data[L-1];data[L-1] = data[0];data[0] =d;L--;Heap_downcast(data,0,L);}cout<<endl;}else {cout<<"exception of input choice sort"<<endl;}}// template function template<class T> void Make_heap(T *data,const int length){if(data != NULL && length >= 0){for(int i=length/2-1;i>=0;i--){Heap_downcast(data,i,length);}}else {cout<<"exception of input make heap"<<endl;}}// template function template<class T> void Heap_downcast(T *data,int i,const int length){if(data != NULL && length >= 0){T max ;// have two childrenwhile(i*2+2 <length){max = data[i];if(max >= data[i*2+1] && max >= data[2*i+2])break;// right child bigger if( data[i*2+2]>data[2*i+1] && data[i*2+2]>max){max = data[i*2+2];data[i*2+2] = data[i];data[i] = max;i = i*2+2;}// left child biggerelse if( data[i*2+1] >= data[2*i+2] && data[i*2+1]>max ){max = data[i*2+1];data[i*2+1] = data[i];data[i] = max;i = i*2+1;}}// have one childif(i*2+1 < length){if(data[i*2+1]>data[i]){max = data[i*2+1];data[i*2+1] = data[i];data[i] = max;}}}else {cout<<"exception of input Heap_downcast"<<endl;}}
0 0
- 算法之排序-----排序第四篇 堆排序
- 《算法(第四版)》排序-----堆排序
- 算法基础之排序篇-堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- 排序算法之 堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- 排序算法之堆排序
- mongodb 分片
- 多线程读取大数据文件
- 【UVaOJ】712 - S-Trees
- HTML4,HTML5,XHTML 之间有什么区别?
- C#调用C++生成的类(通过CLR类库实现)
- 算法之排序-----排序第四篇 堆排序
- Theano的安装
- 字体
- 胖虎白话学习设计模式之外观设计模式(Facade)
- android activity之间传递数据的方式
- 虚拟机不能上网问题的解决
- 小米3 日历 同步google日历
- w3c标准&语义化&模块化
- C#基础篇 数据类型:引用类型