堆排序模板

来源:互联网 发布:unity3d 麻将开发 编辑:程序博客网 时间:2024/05/29 07:35
#pragma warning(disable:4996)#include <iostream>#include <vector>#include <algorithm>#include <queue>#include <string>#include <stdio.h>#include <limits.h>using namespace std;void heap_adjust(vector<int>& nums, int root, int hs){int left = root << 1;int right = (root << 1) + 1;int maxx = root;if (left > hs) return;if (nums[left] > nums[maxx]) maxx = left;if (right <= hs && nums[right] > nums[maxx]) maxx = right;if (maxx != root){swap(nums[maxx], nums[root]);heap_adjust(nums, maxx, hs);}}void build_heap(vector<int>& nums){for (int i = (nums.size()-1) >> 1; i >= 1; i--){heap_adjust(nums, i, nums.size()-1);}}int main(){//the index of heap begins at 1 and index 0 is a placeholdervector<int> heap{0,9,8,7,6,5,5,4,1,2,3,0,5,6,8,7,4,1,5,6};build_heap(heap);for (int i = heap.size() - 1; i >= 2; i--){swap(heap[1], heap[i]);heap_adjust(heap, 1, i-1);}return 0;}

0 0
原创粉丝点击