Pagini recente » Cod sursa (job #942287) | Cod sursa (job #979867) | Cod sursa (job #1588716) | Cod sursa (job #479901) | Cod sursa (job #1905912)
#include <iostream>
#include <fstream>
#include <vector>
template<typename DataType>
class Heap{
private:
std::vector< DataType > heap;
public:
void push(DataType value)//push a element in heap
{
heap.push_back(value);
for(int v = heap.size()-1 ; v != 0; v = (v-1)/2)
{
if(heap[v] < heap[(v-1)/2])
std::swap(heap[v],heap[(v-1)/2]);
else
break;
}
}
size_t size()//number of elements in heap
{
return heap.size();
}
DataType top()//return the top of the heap
{
return heap[0];
}
void pop()//delete the top of the heap
{
std::swap(heap[0],heap[ heap.size()-1 ]);
heap.pop_back();
int v=0;
while(true)
{
if((2*v+1<(int)heap.size() && heap[2*v+1] < heap[v]) && (2*v+2>=(int)heap.size() || !(heap[2*v+2] < heap[2*v+1])))
{
std::swap(heap[v],heap[2*v+1]);
v=2*v+1;
continue;
}
if((2*v+2<(int)heap.size() && heap[2*v+2] < heap[v] && heap[2*v+2] < heap[2*v+1]))
{
std::swap(heap[v],heap[2*v+2]);
v=2*v+2;
continue;
}
break;
}
}
};
template<typename DataType>
void heapSort(std::vector< DataType > &arr)
{
Heap< DataType > H;
while(arr.size())
{
H.push(arr[ arr.size()-1 ]);
arr.pop_back();
}
while(H.size())
{
arr.push_back(H.top());
H.pop();
}
}
int main()
{
int n;
std::vector<int> arr;
std::ifstream in("algsort.in");
in>>n;
for(int i=0;i<n;i++)
{
int x;
in>>x;
arr.push_back(x);
}
in.close();
heapSort(arr);
std::ofstream out("algsort.out");
for(int i=0;i<n;i++)
out<<arr[i]<<' ';
out<<'\n';
out.close();
return 0;
}