#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 placeholder
vector<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;
}
堆排序模板
最新推荐文章于 2023-08-13 19:55:38 发布