堆排序
来源:互联网 发布:移动社交软件 编辑:程序博客网 时间:2024/05/21 11:06
</pre><pre name="code" class="cpp">#include<iostream>using namespace std;class Heap {private: int *data, size;public: Heap(int length_input) { data = new int[length_input]; size = 0; } ~Heap() { delete[] data; } void push(int value) { data[size] = value; int current = size; int father = (current - 1) / 2; while (data[current] > data[father]) { swap(data[current], data[father]); current = father; father = (current - 1) / 2; } size++; } void output() { for (int i = 0; i < size; i++) { cout << data[i] << " "; } cout << endl; } int top() { return data[0]; } void update(int pos, int n) { int lchild = 2 * pos + 1, rchild = 2 * pos + 2; int max_value = pos; if (lchild < n && data[lchild] > data[max_value]) { max_value = lchild; } if (rchild < n && data[rchild] > data[max_value]) { max_value = rchild; } if (max_value != pos) { swap(data[pos], data[max_value]); update(max_value, n); } } void pop() { swap(data[0], data[size - 1]); size--; update(0, size); } void heap_sort() { for(int i=size-1;i>=1;i--) { swap(data[i],data[0]); //最后的元素最小,开始的元素最大,将最大的元素移到最后,再对前面一次更新 update(0,i);//使保持最前面一直是前面最大的,再将其移到最后,便是严格递增的排序 } }};int main() { int arr[10] = { 12, 9, 30, 24, 30, 4, 55, 64, 22, 37 }; Heap heap(100); for (int i = 0; i < 10; i++) { heap.push(arr[i]); } heap.output(); cout << heap.top() << endl; heap.pop(); heap.output(); heap.heap_sort(); heap.output(); return 0;}
0 0
- 堆及堆排序
- 堆/堆排序特点
- 【二叉堆、堆排序】
- 二叉堆 & 堆排序
- 二叉堆 & 堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆和堆排序
- 堆排序(最大堆)
- 堆和堆排序
- 堆和堆排序
- 堆及堆排序
- 堆和堆排序
- 堆与堆排序
- UVA 11134Fabled Rooks
- Tomcat配置虚拟路径
- JSP serverlet区别与联系
- iOS使用GCD或NSTimer定时刷新按钮的文字,按钮文字闪烁的问题
- JS的进阶之路(一)
- 堆排序
- 把一个javabean序列化
- 在Faster RCNN上运行自己的数据集
- 大数据去重,你还在发愁吗?
- JSP九大内置对象及四个作用域
- BestCoder Round #73 (div.2)1002/hdoj5631
- 敏捷带来的新东西
- c++第二次上机实验
- 160319 addChildViewController&transitionFromViewController的使用