博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
O(nLogn)排序 :堆
阅读量:4091 次
发布时间:2019-05-25

本文共 1420 字,大约阅读时间需要 4 分钟。

#include 
#include
#include
using namespace std;void adjust_up(vector
&v, int index){
int parent = 0; int hole = index; int temp = v.at(index); for(; (hole - 1) / 2 >= 0 && hole > 0; hole = parent) {
parent = (hole - 1) / 2; if (temp > v.at(parent)) {
v.at(hole) = v.at(parent); } else {
break; } } v.at(hole) = temp;}void adjust_down(vector
&v, int index, int length){
int child = 0; int hole = index; int temp = v.at(index); for(; hole * 2 + 1 <= length; hole = child) {
child = hole * 2 + 1; if((child + 1 <= length) && (v.at(child + 1) > v.at(child))) {
++child; } if(v.at(child) > temp) {
v.at(hole) = v.at(child); } else {
break; } } v.at(hole) = temp;}void build_heap(vector
&v, int length){ for (int i = (v.size() - 2) / 2; i >= 0; i--) { adjust_down(v, i, length); }}int main(int argc, const char **argv){ auto put = [](vector
&v) { cout << "---" << endl; for (auto &n : v) { cout << n << endl; } }; vector
v { 23, 45, 3, 56, -3, 11}; for(int i = v.size() - 1; i > 0; i--) { build_heap(v, i); std::swap(v.at(0), v.at(i)); } put(v); return 0;}

转载地址:http://krcii.baihongyu.com/

你可能感兴趣的文章
三个方向的人工智能工程师有何不同?
查看>>
超酷炫!5 款图像工具瞬间提高代码逼格!
查看>>
当一个程序员真正掌握算法之后,会变得有多强...
查看>>
我最近在 GitHub 上发现的几个好项目
查看>>
在《我的世界》里从零打造一台计算机有多难?复旦本科生大神花费了一年心血...
查看>>
刷了几千道算法题,这些我私藏的刷题网站都在这里了!
查看>>
做程序员 10 年了,复制粘贴是我最牛逼的技能,直到看了这些大佬分享的公众号干货内容......
查看>>
来,教你做个属于自己的 Markdown 编辑器(代码开源)!
查看>>
废旧 Android 手机如何改造成 Linux 服务器
查看>>
2019 年不可错过的 45 个 AI 开源工具
查看>>
GitHub 上有哪些适合新手跟进的优质项目?
查看>>
IPV4 地址耗尽会对互联网产生什么影响?
查看>>
除了 iTerm,这款高颜值的终端工具也很赞!
查看>>
955 不加班的公司名单:955.WLB
查看>>
2019 年最全 IT 吃瓜指南
查看>>
推荐一位大神,手握 GitHub 16000 star
查看>>
GitHub 上有个沙雕开发者,做了款斗图工具后火了...
查看>>
这才是真正的 Git:Git 内部原理揭秘!
查看>>
微软花2个亿做出来的软件免费用!网友:太良心了!
查看>>
硬核! 逛了 4 年 GitHub,一口气把我收藏的 Java 开源项目分享给你!
查看>>