數(shù)據(jù)結(jié)構(gòu)C++實(shí)現(xiàn)基本的堆

#pragma once

成都創(chuàng)新互聯(lián)公司服務(wù)項目包括清江浦網(wǎng)站建設(shè)、清江浦網(wǎng)站制作、清江浦網(wǎng)頁制作以及清江浦網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,清江浦網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到清江浦省份的部分城市,未來相信會繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!

#include<vector>

#include<queue>

#include<cassert>

#include<iostream>

using namespace std;

//仿函數(shù)實(shí)現(xiàn)在建堆時確定(大小堆)

template<class T>

struct Greater

{

bool operator()(const T& left,const T& right)

{

return left > right;

}

};

template<class T>

struct Less

{

bool operator()(const T& left, const T& right)

{

return left < right;

}

};

template<class T,class Compare = Less<T>>//默認(rèn)建小堆

class Heap

{

public:

Heap()

{

}

Heap(const T* array, size_t size)

{

assert(array);

for (size_t i = 0; i < size; ++i)

{

_vec.push_back(array[i]);

}

for (int i = _vec.size() / 2 - 1; i >= 0; --i)

{

_AdjustDown(_vec, i, _vec.size());

}

}

Heap(const vector<T>& vec)

{

_vec.swap(vec);

for (int i = _vec.size() / 2 - 1; i >= 0; --i)

{

_AdjustDown(_vec, i, _vec.size());

}

}

void Push(const T& x)

{

_vec.push_back(x);

if (_vec.size() > 0)

_AdjustUp(_vec, _vec.size() - 1);

}

void Pop()

{

swap(_vec[0], _vec[_vec.size() - 1]);

_vec.pop_back();

_AdjustDown(_vec, 0, _vec.size());

}

const T& GetTop()

{

assert(_vec.size() > 0);

return _vec[0];

}

bool Empty()

{

return _vec.empty();

}

size_t Size()

{

return _vec.size();

}

private:

void _AdjustDown(vector<T>& vec,int root,int size)

{

int left = root * 2 + 1;

while (left < size)

{

if (left+1 < size && Compare()(vec[left+1], vec[left]))

++left;

if (Compare()(vec[left], vec[root]))

{

swap(vec[left], vec[root]);

root = left;

left = root * 2 + 1;

}

else

break;

}

}

void _AdjustUp(vector<T>& vec,int index)

{

int parent = index >> 1;

while (Compare()(vec[index], vec[parent]))

{

swap(vec[index], vec[parent]);

index = parent;

parent = index >> 1;

}

}

protected:

vector<T> _vec;//底層使用vector來實(shí)現(xiàn)

};

void test()

{

int arr[] = { 1, 2, 8, 9, 7, 4, 6, 5, 11, 10 };

Heap<int> h(arr, sizeof(arr) / sizeof(arr[0]));

h.Push(0);

h.Pop();

cout << h.GetTop() << endl;

h.Pop();

}

文章標(biāo)題:數(shù)據(jù)結(jié)構(gòu)C++實(shí)現(xiàn)基本的堆
本文網(wǎng)址:http://bm7419.com/article20/gihsco.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)移動網(wǎng)站建設(shè)、響應(yīng)式網(wǎng)站、全網(wǎng)營銷推廣、定制網(wǎng)站外貿(mào)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)