#include <iostream>
#include <vector>
#include <random>
using namespace std;
#define left (2*pos+1)
#define right (left+1)
class minHeap
{
public:
minHeap(vector<int> &arr, int size);
int heapIfy(int pos);
int replaceMin(int x);
int returnMin();
private:
vector<int> arr;
int heapsize;
};
int minHeap::heapIfy(int pos)
{
int smallest = pos;
if (left < heapsize && arr[left] < arr[pos])
{
smallest = left;
}
if (right < heapsize && arr[right] < arr[smallest])
{
smallest = right;
}
if (pos != smallest)
{
swap(arr[pos], arr[smallest]);
heapIfy(smallest);
}
return 0;
}
minHeap::minHeap(vector<int> &arr, int heapsize) : arr(arr), heapsize(heapsize)
{
for (int i = heapsize / 2 - 1; i >= 0; --i)
{
heapIfy(i);
}
}
int minHeap::returnMin()
{
int root = arr[0];
if (heapsize > 1)
{
swap(arr[0], arr[heapsize-1]
对接近有序的数组排序 C++
最新推荐文章于 2022-09-27 00:26:56 发布