//@lx BUILD-MAX-HEAP p133
//time: 2010-9-8
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
template <class T>
inline void PRINT_ELEMENTS(const T& col1, const char* optcstr = "")
{
typename T::const_iterator pos;
cout << optcstr;
for(pos = col1.begin(); pos != col1.end(); ++pos)
{
cout << *pos << ' ';
}
cout << endl;
}
int LEFT(int i)
{
return 2*i;
}
int RIGHT(int i)
{
return 2 * i + 1;
}
int PARENT(int i)
{
return i / 2;
}
void exchange(int& a, int& b)
{
int temp = 0;
temp = a;
a = b;
b = temp;
}
template <class T>
void MAX_HEAPIFY(vector<T>& A, int i)
{
int l = LEFT(i);
int r = RIGHT(i);
static int largest;
if(l <= A.size() && A[l-1] > A[i-1])
{
largest = l;
}
else
{
largest = i;
}
if(r <= A.size() && A[r-1] > A[largest-1])
{
largest = r;
}
if(largest != i)
{
exchange(A[i-1], A[largest-1]);
MAX_HEAPIFY(A, largest);
}
}
template <class T>
void BULD_MAX_HEAP(vector<T>& A)
{
int lenght = A.size();
for(int i = lenght / 2; i >= 1; i--)
{
cout << endl << i-1 << endl;
MAX_HEAPIFY(A, i);
PRINT_ELEMENTS(A);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> A;
A.push_back(4);
A.push_back(1);
A.push_back(3);
A.push_back(2);
A.push_back(16);
A.push_back(9);
A.push_back(10);
A.push_back(14);
A.push_back(8);
A.push_back(7);
cout << 5 << endl;
PRINT_ELEMENTS(A);
BULD_MAX_HEAP(A);
return 0;
}
BUILD-MAX-HEAP(A) P133
最新推荐文章于 2022-10-18 15:11:30 发布