Pagini recente » Profil dornescuvlad | Cod sursa (job #2425005) | Cod sursa (job #1118468) | infoarena - comunitate informatica, concursuri de programare | Cod sursa (job #1707971)
#include<iostream>
#include<fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
template<class Type> class Object
{
Type value;
int priority;
public:
Object(){
};
template<class Ttype> Object(Ttype value1, int priority1)
{
value = value1;
priority = priority1;
}
template<class Ttype> void SetValue(Ttype value1)
{
value = value1;
}
Type GetValue()
{
return value;
}
void SetPriority(int priority1)
{
priority = priority1;
}
int GetPriority()
{
return priority;
}
Object* operator = (Object *nod)
{
this->value = nod->GetValue();
this->priority = nod->GetPriority();
return this;
}
void operator == (Object temp1)
{
Object temp;
temp = *this;
*this = temp1;
temp1 = temp;
}
bool operator > (Object obj)
{
if (this->GetPriority() > obj.GetPriority())
return true;
return false;
}
int operator > (string str2)
{
if (strcmp(this->GetValue(), str2) > 0)
return 1;
return -1;
}
bool operator <= (Object obj)
{
if (this->GetPriority() <= obj.GetPriority())
return true;
return false;
}
};
template <class Type> class Heap
{
Object<Type> *a;
public:
void InitializeElements(int numberOfElements)
{
a = new Object<Type>[numberOfElements];
}
Object<Type> GetValue(int index)
{
return a[index];
}
void SetIndex(Object<Type> obj, int index)
{
a[index] = obj;
}
int CompareTo(int i, int j) // -1 for < ; 0 for = ; 1 for >
{
int rez = 0;
Object<Type> firstEle = a[i];
Object<Type> lastEle = a[j];
if (firstEle.GetValue() > lastEle.GetValue())
rez = 1;
else
{
if (firstEle.GetValue() < lastEle.GetValue())
rez = -1;
}
return rez;
}
void max_heapify(int i, int n)
{
int j;
Object<Type> temp;
temp = a[i];
j = 2 * i;
while (j <= n)
{
if (j < n && a[j + 1] > a[j])
j = j + 1;
if (temp > a[j])
break;
else if (temp <= a[j])
{
a[j / 2] = a[j];
j = 2 * j;
}
}
a[j / 2] = temp;
return;
}
void heapsort(int n)
{
Object<Type> temp;
for (int i = n; i >= 2; i--)
{
temp = a[i];
a[i] = a[1];
a[1] = temp;
this->max_heapify(1, i - 1);
}
}
void build_maxheap(int n)
{
int i;
for (i = n / 2; i >= 1; i--)
{
max_heapify(i, n);
}
}
};
int main()
{
int val;
int p;
Object<int> tmp;
Heap<int> h;
int length;
f>>length;
h.InitializeElements(length);
for (int i = 1; i <= length; i++)
{
f>>val;
p=val;
//d[i] = new Object<int>(val,p);
//h.SetIndex(d[i],i);
tmp = new Object<int>(val, p);
h.SetIndex(tmp, i);
}
h.build_maxheap(length);
h.heapsort(length);
for (int i = 1; i <= length; i++)
{
g<<h.GetValue(i).GetValue()<<" ";
}
return 0;
}