堆排序
2015-10-11 22:20
337 查看
#include<iostream> using namespace std; int left(int i) { return 2*i; }//左孩子 int right(int i) { return 2*i+1; }右孩子 void print_array(int *a,size_t length) { for(size_t i = 1;i < length;i++) { cout<<a[i]<<" "; } }//输出数组 void heap_modify(int *a,int i,int heapsize) { while(i<=heapsize) { int l =left(i); int r = right(i); int largest=i,temp; if(l<=heapsize&&a[i]<a[l]) largest =l ; if(r<=heapsize&&a[largest]<a[r]) largest =r ;//得到左右孩子中的最大值 if(i==largest)break; temp=a[largest]; a[largest] = a[i]; a[i] = temp;//交换 i = largest;//下一个节点 //print_array(a,11); //cout<<endl; //cout<<largest <<" "; } } void built_heap(int *a,int length) { for(size_t i = length/2;i>0;i--) { heap_modify(a,i,length); } }//建堆 void heap_sort(int *a,int length) { built_heap(a,length); int heapsize = length-1; for(size_t i = length-1;i>=2;i--) { int temp; temp = a[1]; a[1] = a[i]; a[i] = temp; heapsize--; heap_modify(a,1,heapsize);//最大值拿掉,重新建堆 } } int main() { int a[11] = {0,10,9,8,7,6,5,4,3,2,1};//数组下标0位不使用,从1位开始 cout<<"before heapsort"<<endl; print_array(a,11); cout<<endl; heap_sort(a,11);; cout<<"after heapsort"<<endl; print_array(a,11); }
//解释如注释
相关文章推荐
- 大整数乘法
- Spring注入单例模式问题2
- gns3 1.4.0b3 使用笔记,一些报错的处理
- swift单例和oc单例
- iOS 远程推送
- Foundation
- Linux折腾记录(2)
- Spring注解@Component、@Repository、@Service、@Controller区别
- java入门第二天作业预习运算符
- 夏洛特烦恼 的感想
- [路由交换]OSPF网络类型、DR/BDR、邻居,邻接关系
- 关于”running yum-complete-transaction first” 的提示信息
- 采用maven 对tomcat 进行自动部署
- setAttribute and getAttribute的用法 以及阻止<a>的href的默认属性
- Git 速查手册
- 网站搜索框添加语音搜索功能
- 沟通管理计划包括哪些内容?
- 2015下半年软考系统集成管理工程师10月8日作业
- 在项目中使用volley
- 第四周项目1 建立单链表